package cn.iune.erp.invoice;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.justep.baas.Utils;

import cn.iune.common.response.MapMessage;
import cn.iune.erp.inventory.IStorageRecordDetailService;
import cn.iune.erp.inventory.IStorageRecordService;
import cn.iune.erp.inventory.StorageRecord;
import cn.iune.erp.inventory.StorageRecordDetail;
import cn.iune.erp.setting.ISettingService;



@Transactional
@Service
public class InvoiceServiceImpl implements IInvoiceService {

	@Autowired
	private IAccountInvoiceService accountInvoiceService;
	@Autowired
	private IAccountInvoiceDetailService accountInvoiceDetailService;
	
	@Autowired
	private IStorageRecordService storageRecordService;
	@Autowired
	private IStorageRecordDetailService storageRecordDetailService;
	
	
	@Autowired
	private ISettingService settingService;
	
	

	
	//生成送原厂归还发票
	/*
	public static int insertRepairCGFP(Table idsTable,Map<String, Object> idsMap){
		//首先判断单据类型，获取单据信息
		Map<String,Object> map= idsMap;
		if(map.isEmpty()){
			System.out.println("系统信息-->输入参数为空！");
			return 0;
		}
		int idsCount = (Integer) map.get("idsCount");
		String mergeInvoice = (String) map.get("mergeInvoice");
		//如果mergeInvoice等于"Y"，合并开票，否则等于"";
		
		System.out.println("idsCount-->"+idsCount);
		System.out.println("mergeInvoice-->"+mergeInvoice);

		Iterator<Row> rows=null;
		Row row=null;
		rows = idsTable.iterator();
		while (rows.hasNext()) {
			row = rows.next();
			System.out.println("originFID-->"+row.getString("fID"));
			System.out.println("originBillType-->"+row.getString("billType"));
			String originFID = row.getString("fID");
			String originBillType = row.getString("billType");
			
			//送原厂归还单：
			if(originBillType.equals("YCWG")){
				//赋值
				String enterpriseNo = com.justep.system.context.ContextHelper.getPersonMember().getOgn().getID();
				String enterpriseName = com.justep.system.context.ContextHelper.getPersonMember().getOgn().getFName();
				
				String cUsercode = com.justep.system.context.ContextHelper.getOperator().getCode();
				String cUsername = com.justep.system.context.ContextHelper.getOperator().getName();
				Timestamp cDatetime = com.justep.system.util.CommonUtils.getCurrentDateTime();
				String userId = com.justep.system.context.ContextHelper.getOperator().getID();

				String fID = com.justep.system.util.CommonUtils.createGUID();

				String departmentNo = com.justep.system.context.ContextHelper.getPersonMember().getOrg().getCode();
				String departmentName = com.justep.system.context.ContextHelper.getPersonMember().getOrg().getName();
				String employeeNo = com.justep.system.context.ContextHelper.getOperator().getCode();
				String employeeName = com.justep.system.context.ContextHelper.getOperator().getName();

				String billType = "CGFP";
				String billTypeName = "采购发票";
				
				//读取单据类型属性
				Map<String ,Object> mapBillType = CommonUtil.getBillParam(billType, enterpriseNo);
				if (mapBillType.get("state").equals("failure")){
					System.out.println("系统信息-->单据信息未配置或者系统未启用！");
					return -1;
				}
				
				String systemCode = (String) mapBillType.get("systemCode");
				int flowType = (Integer) mapBillType.get("flowType");
				String revOpay = (String) mapBillType.get("revOpay");
				int direction = (Integer) mapBillType.get("direction");
				
				Date orderDate = com.justep.system.util.CommonUtils.getCurrentDate();
				//读取应收现行会计期间
				System.out.println("systemCode-->"+systemCode);
				Map<String ,Object> mapPeriod = CommonUtil.getCurrentPeriodNo(systemCode, enterpriseNo);
				if(mapPeriod.get("state").equals("failure")){
					System.out.println("系统信息-->应付会计期间未启用或者会计期间未录入！");
					return -1;
				}
				String periodNo = (String) mapPeriod.get("periodNo");
				Date dateStart = (Date) mapPeriod.get("dateStart");
				Date dateEnd = (Date) mapPeriod.get("dateEnd");
				//判断单据日期是否超出会计期间范围
				if (orderDate.before(dateStart) || orderDate.after(dateEnd)){
					//超出范围
					System.out.println("系统信息-->单据日期超出了应付现行会计期间！");
					return -1;
				}
				
				String state = "active";
				String audit = "active";
				String status = "open";
				
				StorageRecordDetailUtil srdu = new StorageRecordDetailUtil();
				StorageRecordDetail repairProcedure = srdu.getByID(originFID);
				
				String origin = repairProcedure.getBillType();
				String originName = repairProcedure.getBillTypeName();
				String originNo = repairProcedure.getRecordDetailNo();

				String accountInvoiceNo = CommonUtil.getBillMaxCode(billType, enterpriseNo);

				String dealObject = "pro";
				String dealObjectLabel = "供应商";
				String customerNo = repairProcedure.getProviderNo();
				String shortName = repairProcedure.getShortName();
				String customerName = repairProcedure.getProviderName();
				
				int taxType = repairProcedure.getTaxType();
				BigDecimal taxRate = repairProcedure.getTaxRate();
				
				String invoiceCategory = null;
				String invoiceCategoryLabel = null;
				String invoiceCode = null;

				BigDecimal orderAmount = BigDecimal.ZERO;
				BigDecimal orderAmountOld = BigDecimal.ZERO;
				BigDecimal orderAmountTax = BigDecimal.ZERO;
				BigDecimal orderAmountTotal = BigDecimal.ZERO;
				
				BigDecimal accountAmountOld = BigDecimal.ZERO;
				BigDecimal accountAmountTax = BigDecimal.ZERO;
				BigDecimal accountAmountTotal = BigDecimal.ZERO;

				BigDecimal orderAmountCleared = BigDecimal.ZERO;
				
				BigDecimal accountAmountCleared = BigDecimal.ZERO;

				String captionNo = null;
				String captionName = null;
				String projectNo = null;
				Date confirmDate = null;
				String comments = "系统自动产生";
				
				String periodStatus = null;
				BigDecimal itemAmount = BigDecimal.ZERO;
				Date invoiceDate = null;
				String tUsercode = null;
				String tUsername = null;
				Timestamp tDatetime = null;
				String eUsercode = null;
				String eUsername = null;
				Timestamp eDatetime = null;
				
				int maxDetailNo = 0;
				int version = 0;

				//插入主表
				IAccountInvoiceService aiu = new AccountInvoiceServiceImpl();
				aiu.insert(fID, systemCode, billType, billTypeName
						, orderDate, flowType, state, audit, status
						, origin, originName, originNo
						, periodStatus, periodNo, accountInvoiceNo, revOpay, direction
						, dealObject, dealObjectLabel, customerNo, shortName, customerName
						, taxType, taxRate, invoiceCategory, invoiceCategoryLabel
						, invoiceCode, invoiceDate
						, itemAmount, orderAmount, orderAmountOld, orderAmountTax, orderAmountTotal
						, accountAmountOld, accountAmountTax, accountAmountTotal
						, orderAmountCleared, accountAmountCleared
						, captionNo, captionName, departmentNo, departmentName, employeeNo, employeeName
						, projectNo, confirmDate, comments
						, cUsercode, cUsername, cDatetime
						, tUsercode, tUsername, tDatetime
						, eUsercode, eUsername, eDatetime
						, maxDetailNo
						, userId, enterpriseNo, enterpriseName
						, version
						);
				
				//插入明细表
				String fDetailID = com.justep.system.util.CommonUtils.createGUID();
				String fMasterID = fID;
				Date billDate = repairProcedure.getConfirmDate();
				
				String itemNo= repairProcedure.getItemNo();
				String itemDescribe = repairProcedure.getItemDescribe();
//				String rationSize = repairProcedure.getRationSize();
				String unitCode = repairProcedure.getUnitCode();
				String unitName = repairProcedure.getUnitName();
				
				itemAmount = repairProcedure.getPriceAmount();
				BigDecimal itemPrice = repairProcedure.getItemPrice();
				
				BigDecimal dealPrice = repairProcedure.getItemPrice();
				
				BigDecimal evaluateQuantityRinse = BigDecimal.ZERO;
				BigDecimal evaluateAmountRinse = BigDecimal.ZERO;
				
				String accountInvoiceDetailNo = accountInvoiceNo+"00001";

				orderAmount = repairProcedure.getOrderAmount();
				orderAmountOld = repairProcedure.getOrderAmountOld();
				orderAmountTax = repairProcedure.getOrderAmountTax();
				orderAmountTotal = repairProcedure.getOrderAmountTotal();
				//计算账款金额
				if(direction==1){
					accountAmountOld = orderAmountOld;
					accountAmountTax = orderAmountTax;
					accountAmountTotal = orderAmountTotal;
				}
				if(direction== -1){
					accountAmountOld = orderAmountOld.negate();
					accountAmountTax = orderAmountTax.negate();
					accountAmountTotal = orderAmountTotal.negate();
				}
				
				
				IAccountInvoiceDetailService aidu = new AccountInvoiceDetailServiceImpl();
				aidu.insert(fDetailID, fMasterID, systemCode, billType, billTypeName
						, orderDate, state, audit, status
						, origin, originName, originNo
						, billDate, dealPrice
						, itemNo, itemDescribe, rationSize, unitCode, unitName
						, itemAmount, itemPrice
						, taxType, taxRate
						, evaluateQuantityRinse, evaluateAmountRinse
						, periodStatus, periodNo, accountInvoiceNo, accountInvoiceDetailNo, revOpay, direction
						, dealObject, dealObjectLabel, customerNo, shortName, customerName
						, orderAmount, orderAmountOld, orderAmountTax, orderAmountTotal
						, captionNo, captionName, departmentNo, departmentName, employeeNo, employeeName
						, projectNo, confirmDate, comments, userId, enterpriseNo, enterpriseName
						, version
						);
				
				//更新主表最大序号
//				AccountInvoiceUtil aiu = new AccountInvoiceUtil();
				aiu.updateMaxDetailNo(fID,1);

				//更新主表的金额
				
//				rtn = accountInvoice.updateTotal(itemQuantity, orderAmount, orderAmountOld, orderAmountTax, orderAmountTotal,  "ModifyState.NEW");
//				if(rtn != 0){
//					return -1;
//				}
				
//				AccountInvoiceUtil aiu = new AccountInvoiceUtil();
				aiu.updateAllAmount(fID, itemAmount, orderAmount, orderAmountOld, orderAmountTax, orderAmountTotal, accountAmountOld, accountAmountTax, accountAmountTotal);
				
				//更新正在开票数量
//				StorageRecordDetailUtil srdu1 = new StorageRecordDetailUtil();
				srdu.updateInvoiceItemQuantityIng(repairProcedure.getRecordDetailNo(),repairProcedure.getBillType(),repairProcedure.getEnterpriseNo(),itemAmount);
				
			}
		}		
		
		
		return 0;
		
	}
	 */
	
	/*
	//生成维修发票
	public static int insertRepairXSFP(Table idsTable,Map<String, Object> idsMap){
		//首先判断单据类型，获取单据信息
		Map<String,Object> map= idsMap;
		if(map.isEmpty()){
			System.out.println("系统信息-->输入参数为空！");
			return 0;
		}
		int idsCount = (Integer) map.get("idsCount");
		String mergeInvoice = (String) map.get("mergeInvoice");
		//如果mergeInvoice等于"Y"，合并开票，否则等于"";
		
		System.out.println("idsCount-->"+idsCount);
		System.out.println("mergeInvoice-->"+mergeInvoice);

		Iterator<Row> rows=null;
		Row row=null;
		rows = idsTable.iterator();
		while (rows.hasNext()) {
			row = rows.next();
			System.out.println("originFID-->"+row.getString("fID"));
			System.out.println("originBillType-->"+row.getString("billType"));
			String originFID = row.getString("fID");
			String originBillType = row.getString("billType");
			String workNo = row.getString("workNo");
			String procedureStep = row.getString("procedureStep");
			
			//维修单：
			if(originBillType.equals("WXDJ") || originBillType.equals("YCWX") || originBillType.equals("XCWX")){
				//赋值
				String enterpriseNo = com.justep.system.context.ContextHelper.getPersonMember().getOgn().getID();
				String enterpriseName = com.justep.system.context.ContextHelper.getPersonMember().getOgn().getFName();
				
				String cUsercode = com.justep.system.context.ContextHelper.getOperator().getCode();
				String cUsername = com.justep.system.context.ContextHelper.getOperator().getName();
				Timestamp cDatetime = com.justep.system.util.CommonUtils.getCurrentDateTime();
				String userId = com.justep.system.context.ContextHelper.getOperator().getID();

				String fID = com.justep.system.util.CommonUtils.createGUID();

				String departmentNo = com.justep.system.context.ContextHelper.getPersonMember().getOrg().getCode();
				String departmentName = com.justep.system.context.ContextHelper.getPersonMember().getOrg().getName();
				String employeeNo = com.justep.system.context.ContextHelper.getOperator().getCode();
				String employeeName = com.justep.system.context.ContextHelper.getOperator().getName();

				String billType = "XSFP";
				String billTypeName = "销售发票";
				
				//读取单据类型属性
				Map<String ,Object> mapBillType = CommonUtil.getBillParam(billType, enterpriseNo);
				if (mapBillType.get("state").equals("failure")){
					System.out.println("系统信息-->单据信息未配置或者系统未启用！");
					return -1;
				}
				
				String systemCode = (String) mapBillType.get("systemCode");
				int flowType = (Integer) mapBillType.get("flowType");
				String revOpay = (String) mapBillType.get("revOpay");
				int direction = (Integer) mapBillType.get("direction");
				
				Date orderDate = com.justep.system.util.CommonUtils.getCurrentDate();
				//读取应收现行会计期间
				System.out.println("systemCode-->"+systemCode);
				Map<String ,Object> mapPeriod = CommonUtil.getCurrentPeriodNo(systemCode, enterpriseNo);
				if(mapPeriod.get("state").equals("failure")){
					System.out.println("系统信息-->应收会计期间未启用或者会计期间未录入！");
					return -1;
				}
				String periodNo = (String) mapPeriod.get("periodNo");
				Date dateStart = (Date) mapPeriod.get("dateStart");
				Date dateEnd = (Date) mapPeriod.get("dateEnd");
				//判断单据日期是否超出会计期间范围
				if (orderDate.before(dateStart) || orderDate.after(dateEnd)){
					//超出范围
					System.out.println("系统信息-->单据日期超出了应收现行会计期间！");
					return -1;
				}
				
				String state = "active";
				String audit = "active";
				String status = "open";
				
				RepairProcedureUtil rpu = new RepairProcedureUtil();
				RepairProcedure repairProcedure = rpu.getByNo(workNo, procedureStep, enterpriseNo);//new RepairProcedure(originFID);
				
				String origin = repairProcedure.getBillType();
				String originName = repairProcedure.getBillTypeName();
				String originNo = repairProcedure.getProduceDetailNo();

				String accountInvoiceNo = CommonUtil.getBillMaxCode(billType, enterpriseNo);

				String dealObject = "cus";
				String dealObjectLabel = "客户";
				RepairOrderUtil rou = new RepairOrderUtil();
				RepairOrder ro = rou.getByID(repairProcedure.getfOrderID());
				
				String customerNo = ro.getCustomerNo();
				String shortName = ro.getShortName();
				String customerName = ro.getCustomerName();
				
				int taxType = repairProcedure.getTaxType();
				BigDecimal taxRate = repairProcedure.getTaxRate();
				
				String invoiceCategory = null;
				String invoiceCategoryLabel = null;
				String invoiceCode = null;

				BigDecimal orderAmount = BigDecimal.ZERO;
				BigDecimal orderAmountOld = BigDecimal.ZERO;
				BigDecimal orderAmountTax = BigDecimal.ZERO;
				BigDecimal orderAmountTotal = BigDecimal.ZERO;
				
				BigDecimal accountAmountOld = BigDecimal.ZERO;
				BigDecimal accountAmountTax = BigDecimal.ZERO;
				BigDecimal accountAmountTotal = BigDecimal.ZERO;

				BigDecimal orderAmountCleared = BigDecimal.ZERO;
				
				BigDecimal accountAmountCleared = BigDecimal.ZERO;

				String captionNo = null;
				String captionName = null;
				String projectNo = null;
				Date confirmDate = null;
				String comments = "系统自动产生";
				
				String periodStatus = null;
				BigDecimal itemAmount = BigDecimal.ZERO;
				Date invoiceDate = null;
				String tUsercode = null;
				String tUsername = null;
				Timestamp tDatetime = null;
				String eUsercode = null;
				String eUsername = null;
				Timestamp eDatetime = null;
				
				int maxDetailNo = 0;
				int version = 0;

				//插入主表
				IAccountInvoiceService aiu = new AccountInvoiceServiceImpl();
				aiu.insert(fID, systemCode, billType, billTypeName
						, orderDate, flowType, state, audit, status
						, origin, originName, originNo
						, periodStatus, periodNo, accountInvoiceNo, revOpay, direction
						, dealObject, dealObjectLabel, customerNo, shortName, customerName
						, taxType, taxRate, invoiceCategory, invoiceCategoryLabel
						, invoiceCode, invoiceDate
						, itemAmount, orderAmount, orderAmountOld, orderAmountTax, orderAmountTotal
						, accountAmountOld, accountAmountTax, accountAmountTotal
						, orderAmountCleared, accountAmountCleared
						, captionNo, captionName, departmentNo, departmentName, employeeNo, employeeName
						, projectNo, confirmDate, comments
						, cUsercode, cUsername, cDatetime
						, tUsercode, tUsername, tDatetime
						, eUsercode, eUsername, eDatetime
						, maxDetailNo
						, userId, enterpriseNo, enterpriseName
						, version
						);
				
				//插入明细表
				String fDetailID = com.justep.system.util.CommonUtils.createGUID();
				String fMasterID = fID;
				Date billDate = repairProcedure.getConfirmDate();
				
//				RepairOrderUtil rou = new RepairOrderUtil();
//				RepairOrder ro = rou.getByID(repairProcedure.getfOrderID());

				String itemNo= ro.getItemNo();
				String itemDescribe = ro.getItemDescribe();
//				String rationSize = ro.getRationSize();
				String unitCode = ro.getUnitCode();
				String unitName = ro.getUnitName();
				
				itemAmount = repairProcedure.getItemAmount();
				BigDecimal itemPrice = repairProcedure.getItemPrice();
				
				BigDecimal dealPrice = repairProcedure.getItemPrice();
				
				BigDecimal evaluateQuantityRinse = BigDecimal.ZERO;
				BigDecimal evaluateAmountRinse = BigDecimal.ZERO;
				
				String accountInvoiceDetailNo = accountInvoiceNo+"00001";

				orderAmount = repairProcedure.getOrderAmount();
				orderAmountOld = repairProcedure.getOrderAmountOld();
				orderAmountTax = repairProcedure.getOrderAmountTax();
				orderAmountTotal = repairProcedure.getOrderAmountTotal();
				//计算账款金额
				if(direction==1){
					accountAmountOld = orderAmountOld;
					accountAmountTax = orderAmountTax;
					accountAmountTotal = orderAmountTotal;
				}
				if(direction== -1){
					accountAmountOld = orderAmountOld.negate();
					accountAmountTax = orderAmountTax.negate();
					accountAmountTotal = orderAmountTotal.negate();
				}
				
				
				IAccountInvoiceDetailService aidu = new AccountInvoiceDetailServiceImpl();
				aidu.insert(fDetailID, fMasterID, systemCode, billType, billTypeName
						, orderDate, state, audit, status
						, origin, originName, originNo
						, billDate, dealPrice
						, itemNo, itemDescribe, rationSize, unitCode, unitName
						, itemAmount, itemPrice
						, taxType, taxRate
						, evaluateQuantityRinse, evaluateAmountRinse
						, periodStatus, periodNo, accountInvoiceNo, accountInvoiceDetailNo, revOpay, direction
						, dealObject, dealObjectLabel, customerNo, shortName, customerName
						, orderAmount, orderAmountOld, orderAmountTax, orderAmountTotal
						, captionNo, captionName, departmentNo, departmentName, employeeNo, employeeName
						, projectNo, confirmDate, comments, userId, enterpriseNo, enterpriseName
						, version
						);
				
				//更新主表最大序号
//				AccountInvoiceUtil aiu = new AccountInvoiceUtil();
				aiu.updateMaxDetailNo(fID,1);

				//更新主表的金额
				
//				rtn = accountInvoice.updateTotal(itemQuantity, orderAmount, orderAmountOld, orderAmountTax, orderAmountTotal,  "ModifyState.NEW");
//				if(rtn != 0){
//					return -1;
//				}
				
//				AccountInvoiceUtil aiu = new AccountInvoiceUtil();
				aiu.updateAllAmount(fID, itemAmount, orderAmount, orderAmountOld, orderAmountTax, orderAmountTotal, accountAmountOld, accountAmountTax, accountAmountTotal);
				
				//更新正在开票数量
//				repairProcedure.updateInvoiceQuantityIng(itemAmount);
				
			}
		}		
		
		
		return 0;
		
	}
	*/

	

	
	/*
	public static List<AccountInvoiceDetail> getAccountInvoiceDetailList(String fMasterID) {
		// TODO Auto-generated method stub
		List<AccountInvoiceDetail> details=new ArrayList<AccountInvoiceDetail>();
		Table table=null;
		Iterator<Row> rows=null;
		Row row=null;
		
		String kSql ;
		
		kSql= " SELECT AccountInvoiceDetail as fDetailID"
			+ " FROM AccountInvoiceDetail AccountInvoiceDetail " 
			+ " WHERE ( AccountInvoiceDetail.fMasterID = :fMasterID ) "
			;
	    //给变量赋值
		Map<String, Object> valuesMap=new HashMap<String, Object>(); 
	    valuesMap.put("fMasterID",fMasterID);

		table = KSQL.select(kSql, valuesMap, "/invoice/bReceivePayable/data", null);
		rows = table.iterator();
		while (rows.hasNext()) {
			row = rows.next();
			String fDetailID = row.getString("fDetailID");
			//填充集合
			AccountInvoiceDetail detail=new AccountInvoiceDetail(fDetailID);
//			System.out.println(fDetailID);
			details.add(detail);
		}
		return details;
//		return null;
	}
	*/
	

	
	
	@Transactional
	private int doItInvoice(AccountInvoice a) {
		//TODO 应收
		///////////////////////////-------------------///////////////////////////////
		//销售发票在审批后挂接销售订单（预收款）关联的优惠券
		//使得优惠券与销售发票关联，在开具正规发票时有用。前提是客户订单是已经预付款的
		/*
		if("1".equals(a.getClearType()) && "XSFP".equals(a.getBillType()) && a.getDepositRate().compareTo(BigDecimal.ZERO)>0 ) {
			//1、根据客户订单号，找到优惠券
			String orderNo = a.getOrderNo();
			if(orderNo!=null && !"".equals(orderNo)) {
				AccountInvoice yhqa = accountInvoiceService.getYHQAByOrderNo(orderNo, a.getEnterpriseNo());
				//2、与销售发票挂接
				if(yhqa!=null) {
					yhqa.setOrigin(a.getBillType());
					yhqa.setOriginName(a.getBillTypeName());
					yhqa.setOriginNo(a.getAccountInvoiceNo());
					accountInvoiceService.update(yhqa);
				}
			}
		}
		*/
		
		///////////////////登记会计账（应收实收/应付实付）////////////////////////////////////////////
		//判断单据为应收还是应付
		/*	
		String periodNoCurrent = "";
		
//		String systemCode = "";
//		if (a.getRevOpay().equals("O") ){
//			systemCode = SystemInfo.SYSTEM_AP;
//		}
//		if (a.getRevOpay().equals("I") ){
//			systemCode = SystemInfo.SYSTEM_AR;
//		}
		
		//获取现行会计期间
//		SystemInfo systemInfo = new SystemInfo(systemCode,a.getEnterpriseNo());
		//首先判断是否启用了会计核算
		String periodStatus = a.getPeriodStatus();
		if ("Y".equals(periodStatus)){
			//启用了会计核算
			periodNoCurrent = a.getPeriodNo();

			//计入期间总账
			String revOpay = a.getRevOpay();
//			String dealObject = a.getDealObject();
//			String dealObjectLabel = a.getDealObjectLabel();
			String customerNo = a.getCustomerNo();
//			String shortName = a.getShortName();
//			String objectName = a.getCustomerName();
			
//			String departmentNo = "";
//			if (a.getDepartmentNo()!=null){
//				departmentNo = a.getDepartmentNo();
//			}
//			String departmentName = "";
//			if (a.getDepartmentName()!=null){
//				departmentName = a.getDepartmentName();
//			}
//			String employeeNo = a.getEmployeeNo();
//			String employeeName = a.getEmployeeName();
			
			String enterpriseNo = a.getEnterpriseNo();
			String enterpriseName = a.getEnterpriseName();
			String billType = a.getBillType();
			String billTypeName = a.getBillTypeName();

			BigDecimal invoiceAmount = BigDecimal.ZERO;
			BigDecimal actualAmount = BigDecimal.ZERO;

			//登记会计期间明细账
			IAccountInvoicePeriodDetailService arppu = new AccountInvoicePeriodDetailService();
//			AccountRPDetailPeriod accountInvoicePeriodDetailCurrent=new AccountRPDetailPeriod(revOpay, periodNoCurrent, dealObject, objectCode, enterpriseNo,billType);
			//判断单据为应收应付
			if (a.getBillType().equals("CGFP") 
					|| a.getBillType().equals("QTYF") 
					|| a.getBillType().equals("XSFP") 
					|| a.getBillType().equals("QTYS")
					){
				invoiceAmount = a.getAccountAmountTotal();
				arppu.updateAllAmount(revOpay, periodNoCurrent
					, customerNo
					, billType,billTypeName
					, invoiceAmount, actualAmount
					, null
					, enterpriseNo, enterpriseName
					);
			}
			
		}
		*/

		return 0;

	}
	
	@Transactional
	private int unDoInvoice(AccountInvoice a) {
		//TODO 应收
		///////////////////////////-------------------///////////////////////////////
		//销售发票在审批后挂接销售订单（预收款）关联的优惠券
		//使得优惠券与销售发票关联，在开具正规发票时有用。前提是客户订单是已经预付款的
		/*
		if("1".equals(a.getClearType()) && "XSFP".equals(a.getBillType()) && a.getDepositRate().compareTo(BigDecimal.ZERO)>0 ) {
			//1、根据客户订单号，找到优惠券
			String orderNo = a.getOrderNo();
			if(orderNo!=null && !"".equals(orderNo)) {
				AccountInvoice yhqa = accountInvoiceService.getYHQAByOrderNo(orderNo, a.getEnterpriseNo());
				//2、与销售发票挂接
				if(yhqa!=null) {
					yhqa.setOrigin("XSDD");
					yhqa.setOriginName("销售订单");
					yhqa.setOriginNo(a.getOrderNo());
					accountInvoiceService.update(yhqa);
				}
			}
		}
		*/
		
		////////////////////////////登记会计账（应收实收/应付实付）////////////////////////////////////////////
		/*
		String periodNoCurrent = "";
		
//		String systemCode = "";
//		if (a.getRevOpay().equals("O")){
//			systemCode = SystemInfo.SYSTEM_AP;
//		}
//		if (a.getRevOpay().equals("I") ){
//			systemCode = SystemInfo.SYSTEM_AR;
//		}
		
		//获取现行会计期间
//		SystemInfo systemInfo = new SystemInfo(systemCode,a.getEnterpriseNo());
		//首先判断是否启用了会计核算
		String periodStatus = a.getPeriodStatus();
		if ("Y".equals(periodStatus)){
			//启用了会计核算
			periodNoCurrent = a.getPeriodNo();

			//计入期间总账
			String revOpay = a.getRevOpay();
//			String dealObject = a.getDealObject();
//			String dealObjectLabel = a.getDealObjectLabel();
			String customerNo = a.getCustomerNo();
//			String shortName = a.getShortName();
//			String objectName = a.getCustomerName();
			
//			String departmentNo = "";
//			if (a.getDepartmentNo()!=null){
//				departmentNo = a.getDepartmentNo();
//			}
//			String departmentName = "";
//			if (a.getDepartmentName()!=null){
//				departmentName = a.getDepartmentName();
//			}
//			String employeeNo = a.getEmployeeNo();
//			String employeeName = a.getEmployeeName();
			
			String enterpriseNo = a.getEnterpriseNo();
			String enterpriseName = a.getEnterpriseName();
			String billType = a.getBillType();
			String billTypeName = a.getBillTypeName();

			BigDecimal invoiceAmount = BigDecimal.ZERO;
			BigDecimal actualAmount = BigDecimal.ZERO;
			//登记会计期间明细账
			IAccountInvoicePeriodDetailService arppu = new AccountInvoicePeriodDetailService();
//			AccountRPDetailPeriod accountInvoicePeriodDetailCurrent=new AccountRPDetailPeriod(revOpay, periodNoCurrent, dealObject, objectCode, enterpriseNo,billType);
			//判断单据为应收应付
			if (a.getBillType().equals("CGFP") 
					|| a.getBillType().equals("QTYF") 
					|| a.getBillType().equals("XSFP") 
					|| a.getBillType().equals("QTYS")
					){
				invoiceAmount = a.getAccountAmountTotal().negate();
				arppu.updateAllAmount(revOpay, periodNoCurrent
					, customerNo
					, billType,billTypeName
					, invoiceAmount, actualAmount
					, null
					, enterpriseNo, enterpriseName
					);
			}
		}
		*/

		return 0;

	}

	
	@Transactional
	private int doItInvoiceDetail(AccountInvoiceDetail accountInvoiceDetail){
		//更新相关单据

		//TODO:应收实收分类
		//TODO 应收
		//一、销售发票
		if(accountInvoiceDetail.getBillType().equals("XSFP")){
			
			//更新销售发货单的开票数量和开票金额
			if ((accountInvoiceDetail.getOrigin().equals("XSCK") 
					|| accountInvoiceDetail.getOrigin().equals("XSRK")
//					|| accountInvoiceDetail.getOrigin().equals("WXFL")
//					|| accountInvoiceDetail.getOrigin().equals("WXTL")
//					|| accountInvoiceDetail.getOrigin().equals("XCFL")
//					|| accountInvoiceDetail.getOrigin().equals("XCTL")
					) && Utils.isNotEmptyString(accountInvoiceDetail.getOriginNo()) && Utils.isNotEmptyString(accountInvoiceDetail.getOriginSerialNo())){

				storageRecordDetailService.updateInvoiceItemQuantity(accountInvoiceDetail.getOriginNo(), accountInvoiceDetail.getOriginSerialNo(), accountInvoiceDetail.getEnterpriseNo(),accountInvoiceDetail.getItemAmount());
			}
			
			//更新维修单的开票数量和开票金额
			if ((accountInvoiceDetail.getOrigin().equals("WXDJ") 
					|| accountInvoiceDetail.getOrigin().equals("YCWX")
					|| accountInvoiceDetail.getOrigin().equals("XCWX")
			)&& accountInvoiceDetail.getOriginNo()!=null){
				/*
				RepairProcedure repairProcedure = new RepairProcedure(accountInvoiceDetail.getOriginNo(),accountInvoiceDetail.getEnterpriseNo());
				actionResult = repairProcedure.updateInvoiceQuantity(accountInvoiceDetail.getItemAmount());
				*/
			}
			
			
			
		}
		
		
		//TODO：应付实付分类
		//TODO 应付
		//二、采购发票
		if(accountInvoiceDetail.getBillType().equals("CGFP")){
			
			//TODO:处理应付相关单据

			if ((accountInvoiceDetail.getOrigin().equals("CGRK") 
					|| accountInvoiceDetail.getOrigin().equals("CGCK")
					|| accountInvoiceDetail.getOrigin().equals("WWRK") 
					|| accountInvoiceDetail.getOrigin().equals("WWCK")
					|| accountInvoiceDetail.getOrigin().equals("GYZY")
					|| accountInvoiceDetail.getOrigin().equals("GYRK")
					|| accountInvoiceDetail.getOrigin().equals("GYCK")
					|| accountInvoiceDetail.getOrigin().equals("YCWG")
					) && Utils.isNotEmptyString(accountInvoiceDetail.getOriginNo()) && Utils.isNotEmptyString(accountInvoiceDetail.getOriginSerialNo())){

				
				//委外发票：无需在此写入成本，因为委外工单属于工单，工单的入库成本需要在”成本计算“子系统中计算获得
				/*
				存货的采购成本：包括购买价款、相关税费、运输费、装卸费、保险费以及其他可归属于存货采购成本的费用。
				　　其中，
				　　(1)存货的购买价款是指企业购入的材料或商品的发票账单上列明的价款，但不包括按规定可以抵扣的增值税额。
				　　(2)存货的相关税费是指企业购买存货发生的进口关税、消费税、资源税和不能抵扣的增值税进项税额以及相应的教育费附加等应计入存货采购成本的税费。
				　　对于增值税小规模纳税人购进存货所支付的增值税不能抵扣，应计入存货的采购成本中。
				　　(3)其他可归属于存货采购成本的费用是指采购成本中除上述各项以外的可归属于存货采购的费用，如在存货采购过程中发生的仓储费、包装费、运输途中的合理损耗、入库前的挑选整理费用等。
				　　注意：商品流通企业在采购商品过程中发生的运输费、装卸费、保险费以及其他可归属于存货采购成本的费用等进货费用。
				　　①应当计入存货采购成本
				　　②也可以先进行归集，期末根据所购商品的存销情况进行分摊。对于已售商品的进货费用，计入当期损益;对于未售商品的进货费用，计入期末存货成本。
				　　③企业采购商品的进货费用金额较小的，可以在发生时直接计入当期损益。
				
				增值税抵扣
				增值税是对销售货物或者提供加工、修理修配劳务以及进口货物的单位和个人就其实现的增值额征收的一个税种。增值税抵扣：应交的税费=销项税-进项税。
				
				举例
				如某厂进原料，不含税价100元，17%税率，增值税进项税17元，合计含税价117元。
				加工后卖出，不含税价200元，17%税率，增值税销项税34元，合计含税价234元。
				
				一般纳税人企业可以凭那张进货的增值税发票的抵扣联去当地国税机关认证，期限是自开票日起180天。
				认证后的增值税发票可以冲抵销项税额：
				譬如上例中的进项税17元可以冲抵销项税34元，则实际交纳的销项税为17元。
				增值税一般纳税人取得2010年1月1日以后开具的增值税专用发票、公路内河货物运输业统一发票和机动车销售统一发票，应在开具之日起180日内到税务机关办理认证，并在认证通过的次月申报期内，向主管税务机关申报抵扣进项税额。
				*/
				
				//企业为一般纳税人：进项税不作为进货成本，因为进项税可以用来抵扣销项税（增值税专用发票A）；
				//企业为小规模纳税人：进项税作为进货成本（增值税普通发票B）；
				
				///////////////////////////////////////////////////////////
				//系统参数设置
//				ParamSetting paramSetting = paramSettingService.getByNo(accountInvoiceDetail.getEnterpriseNo());
//				//采用成本制度【0：标准成本制，1：实际成本制】
//				int costingRules = 1;
//				if(paramSetting!=null) {
//					costingRules = paramSetting.getCostingRules();
//				}
				
				/*
				$scope.dataCostingType = [
				              			{"costingType":1,"costingTypeLabel":"1:移动加权平均"}
				              			,{"costingType":2,"costingTypeLabel":"2:月末一次加权加权平均"}
										,{"costingType":3,"costingTypeLabel":"3:先进先出X"}
										,{"costingType":4,"costingTypeLabel":"4:个别计价（分批认定）X"}
				              			];
				*/
				//成本计价方式
//				int costingType = paramSetting.getCostingType();
				
				//成本计价方式
//				int costingType = fileItem.getCostingType();
//				System.out.println("成本计价方式costingType-->>"+costingType);
				///////////////////////////////////////////////////////////////
				
				//计算采购入库单成本及入库单单位成本
				//采购发票：将开票金额写入进货成本。
				//无论是标准成本法还是实际成本法，都需要在开票时将采购成本写入采购进货单的实际成本中
				//考虑库存成本更新
				if (accountInvoiceDetail.getOrigin().equals("CGRK") 
						|| accountInvoiceDetail.getOrigin().equals("CGCK")
						|| accountInvoiceDetail.getOrigin().equals("WWRK") 
						|| accountInvoiceDetail.getOrigin().equals("WWCK")
						){
					//采购成本
					BigDecimal costingAmount = accountInvoiceDetail.getOrderAmountOld();
					/////////////////////////////////////////////////////////////////////
					//非增值税专用发票，需要进项税作为进货成本；
					if(!"S".equals(accountInvoiceDetail.getInvoiceCategory())) {
						costingAmount = costingAmount.add(accountInvoiceDetail.getOrderAmountTax());
					}
					
					//成本合计
					//成本符号
					costingAmount = costingAmount.multiply(new BigDecimal(accountInvoiceDetail.getDirection())).setScale(2, BigDecimal.ROUND_HALF_UP);
					/////////////////////////////////////////////////////////////////////
					
					storageRecordDetailService.updateInvoiceItemQuantity(accountInvoiceDetail.getOriginNo(), accountInvoiceDetail.getOriginSerialNo(), accountInvoiceDetail.getEnterpriseNo(),accountInvoiceDetail.getItemAmount(), costingAmount);
					
				}
				
				/*
				//首先判断是否存在暂估成本核算单
				if(storageRecordDetail.getEvaluateQuantity().compareTo(BigDecimal.ZERO)!=0){
					//处理蓝字暂估成本（ZGCB），生成红字暂估回冲（ZGHC）
					//1、月初回冲
					//2、单到回冲
					//首先获取蓝字暂估成本核算单，作为红字暂估回冲单的数据来源
					
					//插入红字暂估回冲单
					//accountInvoiceDetail.insertDetailHX(systemCode, billType, billTypeName, orderAmount, orderAmountOld, orderAmountTax, orderAmountTotal, accountAmountOld, accountAmountTax, accountAmountTotal, io, direction, periodNo, confirmDate, confirmDate, accountInvoiceNo, accountInvoiceDetailNo, dealObject, customerNo, shortName, customerName, origin, originName, originNo, invoiceCategory, invoiceCategoryLabel, invoiceCode, confirmDate, enterpriseNo, enterpriseName, departmentNo, departmentName, employeeNo, employeeName, projectNo, comments, captionNo, captionName)
					
					//3、单到补差
				}
				*/
				
			}

		}
		
		//三、暂估成本
		if(accountInvoiceDetail.getBillType().equals("ZGCB")){
			//更新采购进货单单的暂估数量和暂估金额
			if ((accountInvoiceDetail.getOrigin().equals("CGRK") 
					|| accountInvoiceDetail.getOrigin().equals("CGCK")
					|| accountInvoiceDetail.getOrigin().equals("WWRK") 
					|| accountInvoiceDetail.getOrigin().equals("WWCK")
					) && Utils.isNotEmptyString(accountInvoiceDetail.getOriginNo()) && Utils.isNotEmptyString(accountInvoiceDetail.getOriginSerialNo())){
				//采购成本
				BigDecimal costingAmount = accountInvoiceDetail.getOrderAmountOld();
				/////////////////////////////////////////////////////////////////////
				//非增值税专用发票，需要进项税作为进货成本；
				if(!"S".equals(accountInvoiceDetail.getInvoiceCategory())) {
					costingAmount = costingAmount.add(accountInvoiceDetail.getOrderAmountTax());
				}
				
				//成本合计
				//成本符号
				costingAmount = costingAmount.multiply(new BigDecimal(accountInvoiceDetail.getDirection())).setScale(2, BigDecimal.ROUND_HALF_UP);
				/////////////////////////////////////////////////////////////////////

				storageRecordDetailService.updateEvaluateItemQuantity(accountInvoiceDetail.getOriginNo(), accountInvoiceDetail.getOriginSerialNo(), accountInvoiceDetail.getEnterpriseNo(), accountInvoiceDetail.getItemAmount(), costingAmount);
			}
		}
		
		///////////////////////////////////////////////////////////////////////
		//资产借入借出管理
		/*
		//资产借出
		if(accountInvoiceDetail.getBillType().equals("ZCJC")){
			//资产借出单
			String assetsID = accountInvoiceDetail.getItemID();
			String dealObjectID = accountInvoiceDetail.getCustomerID();
			String dealObjectNo = accountInvoiceDetail.getCustomerNo();
			String shortName = accountInvoiceDetail.getShortName();
			String dealObjectName = accountInvoiceDetail.getCustomerName();
			String fPhone = accountInvoiceDetail.getfPhone();
			String audit = accountInvoiceDetail.getAudit();
			int rtn = 0;
			rtn = assetsInfoService.pickRegister(assetsID, dealObjectID, dealObjectNo, shortName, dealObjectName, fPhone, audit);
			if(rtn!=0){
				System.out.println("更新资产台账错误！");
			}
		}

		//借出归还
		if(accountInvoiceDetail.getBillType().equals("ZCGH")){
			//资产归还单
			String assetsID = accountInvoiceDetail.getItemID();
			String dealObjectID = accountInvoiceDetail.getCustomerID();
			String dealObjectNo = accountInvoiceDetail.getCustomerNo();
			String shortName = accountInvoiceDetail.getShortName();
			String dealObjectName = accountInvoiceDetail.getCustomerName();
			String fPhone = accountInvoiceDetail.getfPhone();
			String audit = accountInvoiceDetail.getAudit();
			int rtn = 0;
			rtn = assetsInfoService.storeRegister(assetsID, dealObjectID, dealObjectNo, shortName, dealObjectName, fPhone, audit);
			if(rtn!=0){
				System.out.println("更新资产台账错误！");
			}
			if (accountInvoiceDetail.getOrigin().equals("ZCJC") && accountInvoiceDetail.getOriginNo()!=null){
				//更新归还数量
				accountInvoiceDetailService.updateEvaluateQuantityRinse(accountInvoiceDetail.getOriginNo(),accountInvoiceDetail.getOriginSerialNo(), accountInvoiceDetail.getEnterpriseNo(),accountInvoiceDetail.getAudit());
			}

		}

		//资产清理
		if(accountInvoiceDetail.getBillType().equals("ZCQL")){
			//资产清理单
			String assetsID = accountInvoiceDetail.getItemID();
			String dealObjectID = accountInvoiceDetail.getCustomerID();
			String dealObjectNo = accountInvoiceDetail.getCustomerNo();
			String shortName = accountInvoiceDetail.getShortName();
			String dealObjectName = accountInvoiceDetail.getCustomerName();
			String fPhone = accountInvoiceDetail.getfPhone();
			String audit = accountInvoiceDetail.getAudit();
			int rtn = 0;
			rtn = assetsInfoService.clearRegister(assetsID, dealObjectID, dealObjectNo, shortName, dealObjectName, fPhone, audit);
			if(rtn!=0){
				System.out.println("更新资产台账错误！");
			}
		}
		*/
		
		
		return 0;
	}
	
	@Transactional
	private int unDoInvoiceDetail(AccountInvoiceDetail accountInvoiceDetail){
		//更新相关单据

		//TODO:应收实收分类
		//一、销售发票
		if(accountInvoiceDetail.getBillType().equals("XSFP")){
						
			//更新销售发货单的开票数量和开票金额
			if ((accountInvoiceDetail.getOrigin().equals("XSCK") 
					|| accountInvoiceDetail.getOrigin().equals("XSRK")
//					|| accountInvoiceDetail.getOrigin().equals("WXFL")
//					|| accountInvoiceDetail.getOrigin().equals("WXTL")
//					|| accountInvoiceDetail.getOrigin().equals("XCFL")
//					|| accountInvoiceDetail.getOrigin().equals("XCTL")
					) && Utils.isNotEmptyString(accountInvoiceDetail.getOriginNo()) && Utils.isNotEmptyString(accountInvoiceDetail.getOriginSerialNo())){
				
				storageRecordDetailService.updateInvoiceItemQuantity(accountInvoiceDetail.getOriginNo(), accountInvoiceDetail.getOriginSerialNo(), accountInvoiceDetail.getEnterpriseNo(),accountInvoiceDetail.getItemAmount().negate());
			}		
			
			//更新维修单的开票数量和开票金额
			if ((accountInvoiceDetail.getOrigin().equals("WXDJ") 
					|| accountInvoiceDetail.getOrigin().equals("YCWX")
					|| accountInvoiceDetail.getOrigin().equals("XCWX")
			) && accountInvoiceDetail.getOriginNo()!=null){
				/*
				RepairProcedure repairProcedure = new RepairProcedure(accountInvoiceDetail.getOriginNo(),accountInvoiceDetail.getEnterpriseNo());
				actionResult = repairProcedure.updateInvoiceQuantity(accountInvoiceDetail.getItemAmount().negate());
				*/
			}

		}

		//TODO:应付实付分类
		//二、采购发票
		if(accountInvoiceDetail.getBillType().equals("CGFP")){

			//处理应付相关单据
			//更新采购进货单单的开票数量和开票金额
			//委外入库单//工艺转移单//工艺入库单
			if ((accountInvoiceDetail.getOrigin().equals("CGRK") 
					|| accountInvoiceDetail.getOrigin().equals("CGCK")
					|| accountInvoiceDetail.getOrigin().equals("WWRK") 
					|| accountInvoiceDetail.getOrigin().equals("WWCK")
					|| accountInvoiceDetail.getOrigin().equals("GYZY")
					|| accountInvoiceDetail.getOrigin().equals("GYRK")
					|| accountInvoiceDetail.getOrigin().equals("GYCK")
					) && Utils.isNotEmptyString(accountInvoiceDetail.getOriginNo()) && Utils.isNotEmptyString(accountInvoiceDetail.getOriginSerialNo())){
				
				//计算采购入库单成本及入库单单位成本
				//采购发票：将开票金额写入进货成本。
				//无论是标准成本法还是实际成本法，都需要在开票时将采购成本写入采购进货单的实际成本中
				//考虑库存成本更新
				if (accountInvoiceDetail.getOrigin().equals("CGRK") 
						|| accountInvoiceDetail.getOrigin().equals("CGCK")
						|| accountInvoiceDetail.getOrigin().equals("WWRK") 
						|| accountInvoiceDetail.getOrigin().equals("WWCK")
						){
					//采购成本
					BigDecimal costingAmount = accountInvoiceDetail.getOrderAmountOld();
					/////////////////////////////////////////////////////////////////////
					//非增值税专用发票，需要进项税作为进货成本；
					if(!"S".equals(accountInvoiceDetail.getInvoiceCategory())) {
						costingAmount = costingAmount.add(accountInvoiceDetail.getOrderAmountTax());
					}
					
					//成本合计
					//成本符号
					costingAmount = costingAmount.multiply(new BigDecimal(accountInvoiceDetail.getDirection())).setScale(2, BigDecimal.ROUND_HALF_UP);
					/////////////////////////////////////////////////////////////////////
				
					storageRecordDetailService.updateInvoiceItemQuantity(accountInvoiceDetail.getOriginNo(), accountInvoiceDetail.getOriginSerialNo(), accountInvoiceDetail.getEnterpriseNo(),accountInvoiceDetail.getItemAmount().negate(), costingAmount.negate());
				}
			}
			
		}
		
		//三、暂估成本
		if(accountInvoiceDetail.getBillType().equals("ZGCB")){
			//更新采购进货单单的暂估数量和暂估金额
			if ((accountInvoiceDetail.getOrigin().equals("CGRK") 
					|| accountInvoiceDetail.getOrigin().equals("CGCK")
					|| accountInvoiceDetail.getOrigin().equals("WWRK") 
					|| accountInvoiceDetail.getOrigin().equals("WWCK")
					) && Utils.isNotEmptyString(accountInvoiceDetail.getOriginNo()) && Utils.isNotEmptyString(accountInvoiceDetail.getOriginSerialNo())){
				//采购成本
				BigDecimal costingAmount = accountInvoiceDetail.getOrderAmountOld();
				/////////////////////////////////////////////////////////////////////
				//非增值税专用发票，需要进项税作为进货成本；
				if(!"S".equals(accountInvoiceDetail.getInvoiceCategory())) {
					costingAmount = costingAmount.add(accountInvoiceDetail.getOrderAmountTax());
				}
				
				//成本合计
				//成本符号
				costingAmount = costingAmount.multiply(new BigDecimal(accountInvoiceDetail.getDirection())).setScale(2, BigDecimal.ROUND_HALF_UP);
				/////////////////////////////////////////////////////////////////////

				storageRecordDetailService.updateEvaluateItemQuantity(accountInvoiceDetail.getOriginNo(), accountInvoiceDetail.getOriginSerialNo(), accountInvoiceDetail.getEnterpriseNo(), accountInvoiceDetail.getItemAmount().negate(), costingAmount.negate());
			}
		}
		
		
		///////////////////////////////////////////////////////////////////////
		//资产借入借出管理
		/*
		//资产借出
		if(accountInvoiceDetail.getBillType().equals("ZCJC")){
			//资产借出单
			String assetsID = accountInvoiceDetail.getItemID();
			String dealObjectID = accountInvoiceDetail.getCustomerID();
			String dealObjectNo = accountInvoiceDetail.getCustomerNo();
			String shortName = accountInvoiceDetail.getShortName();
			String dealObjectName = accountInvoiceDetail.getCustomerName();
			String fPhone = accountInvoiceDetail.getfPhone();
			String audit = accountInvoiceDetail.getAudit();
			int rtn = 0;
			rtn = assetsInfoService.pickRegister(assetsID, dealObjectID, dealObjectNo, shortName, dealObjectName, fPhone, audit);
			if(rtn!=0){
				System.out.println("更新资产台账错误！");
			}
		}

		//借出归还
		if(accountInvoiceDetail.getBillType().equals("ZCGH")){
			//资产归还单
			String assetsID = accountInvoiceDetail.getItemID();
			String dealObjectID = accountInvoiceDetail.getCustomerID();
			String dealObjectNo = accountInvoiceDetail.getCustomerNo();
			String shortName = accountInvoiceDetail.getShortName();
			String dealObjectName = accountInvoiceDetail.getCustomerName();
			String fPhone = accountInvoiceDetail.getfPhone();
			String audit = accountInvoiceDetail.getAudit();
			int rtn = 0;
			rtn = assetsInfoService.storeRegister(assetsID, dealObjectID, dealObjectNo, shortName, dealObjectName, fPhone, audit);
			if(rtn!=0){
				System.out.println("更新资产台账错误！");
			}
			if (accountInvoiceDetail.getOrigin().equals("ZCJC") && accountInvoiceDetail.getOriginNo()!=null){
				//更新归还数量
				accountInvoiceDetailService.updateEvaluateQuantityRinse(accountInvoiceDetail.getOriginNo(), accountInvoiceDetail.getOriginSerialNo(), accountInvoiceDetail.getEnterpriseNo(),accountInvoiceDetail.getAudit());
			}
		}

		//资产清理
		if(accountInvoiceDetail.getBillType().equals("ZCQL")){
			//资产清理单
			String assetsID = accountInvoiceDetail.getItemID();
			String dealObjectID = accountInvoiceDetail.getCustomerID();
			String dealObjectNo = accountInvoiceDetail.getCustomerNo();
			String shortName = accountInvoiceDetail.getShortName();
			String dealObjectName = accountInvoiceDetail.getCustomerName();
			String fPhone = accountInvoiceDetail.getfPhone();
			String audit = accountInvoiceDetail.getAudit();
			int rtn = 0;
			rtn = assetsInfoService.clearRegister(assetsID, dealObjectID, dealObjectNo, shortName, dealObjectName, fPhone, audit);
			if(rtn!=0){
				System.out.println("更新资产台账错误！");
			}
		}
		*/

		return 0;
	}
	
	
	@Transactional
	@Override
    public void afterInsertInvoice(AccountInvoice obj){
		//////////////////////////////////////////////////////////////////////////////////////////
		if("XSFP".equals(obj.getBillType())){
			if ("XSCK".equals(obj.getOrigin()) && obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				String next, nextName, nextNo;
				next = obj.getBillType();
				nextName = obj.getBillTypeName();
				nextNo = obj.getAccountInvoiceNo();
				storageRecordService.updateNextNo(obj.getOriginNo(),obj.getEnterpriseNo(), next, nextName, nextNo);
			}
		}

	}
	
	@Transactional
	@Override
    public void beforeUpdateInvoice(AccountInvoice obj) throws IllegalArgumentException, IllegalAccessException{

    	//java遍历实体类的属性和值
    	/*
    	Class<? extends AccountInvoice> cls = obj.getClass();  
        Field[] fields = cls.getDeclaredFields();  
        for(int i=0; i<fields.length; i++){  
            Field f = fields[i];  
            f.setAccessible(true);  
            System.out.println("属性名:" + f.getName() + " 属性值:" + f.get(obj));  
        } 
    	
        System.out.println("--------------------------------------------------------");
        AccountInvoice objDb = accountInvoiceService.getByID(obj.getfID());
        
    	Class<? extends AccountInvoice> cls2 = objDb.getClass();  
        Field[] fields2 = cls2.getDeclaredFields();  
        for(int i=0; i<fields2.length; i++){  
            Field f = fields2[i];  
            f.setAccessible(true);  
            System.out.println("属性名:" + f.getName() + " 属性值:" + f.get(objDb));  
        } 
        */

	}
	
	@Transactional
	@Override
    public void afterUpdateInvoice(AccountInvoice obj){
		/*
		if("1".equals(obj.getClearType()) && obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())){
			if ("XSCK".equals(obj.getOrigin())) {
				storageRecordService.updatePaymentStatus(obj.getOriginNo(),obj.getEnterpriseNo(), obj.getHandling());
			}
		}
		*/

	}
	
	@Transactional
	@Override
    public void beforeDeleteInvoice(String fID){
		AccountInvoice obj = accountInvoiceService.getByID(fID);
		//////////////////////////////////////////////////////////////////////////////////////////
		if("XSFP".equals(obj.getBillType())){
			if ("XSCK".equals(obj.getOrigin()) && obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				String next, nextName, nextNo;
				next = null;
				nextName = null;
				nextNo = null;
				storageRecordService.updateNextNo(obj.getOriginNo(),obj.getEnterpriseNo(), next, nextName, nextNo);
			}
		}

	}

	@Transactional
	@Override
    public void afterInsertInvoiceDetail(AccountInvoiceDetail obj){
		//销售发票
		if(obj.getBillType().equals("XSFP")){
			
			if ((obj.getOrigin().equals("XSCK") 
					|| obj.getOrigin().equals("XSRK")
//					|| obj.getOrigin().equals("WXFL")
//					|| obj.getOrigin().equals("WXTL")
//					|| obj.getOrigin().equals("XCFL")
//					|| obj.getOrigin().equals("XCTL")
					) && Utils.isNotEmptyString(obj.getOriginNo()) && Utils.isNotEmptyString(obj.getOriginSerialNo())){

				//如果数据来源是销售发货单，则更新正在开票数量
				//插入
//				System.out.println("obj.getOriginNo()-->"+obj.getOriginNo());
//				System.out.println("obj.getOrigin()-->"+obj.getOrigin());
//				System.out.println("obj.getEnterpriseNo()-->"+obj.getEnterpriseNo());
//				System.out.println("obj.getItemAmount()-->"+obj.getItemAmount());
				storageRecordDetailService.updateInvoiceItemQuantityIng(obj.getOriginNo(),obj.getOriginSerialNo(), obj.getEnterpriseNo(),obj.getItemAmount());
			}
			if (obj.getOrigin().equals("WXDJ") 
					|| obj.getOrigin().equals("YCWX")
					|| obj.getOrigin().equals("XCWX")
					){
				//如果数据来源是销售发货单，则更新正在开票数量
				//插入
				
//				RepairProcedure repairProcedure= new RepairProcedure(obj.getOriginNo(), obj.getEnterpriseNo());
//				iReturn=repairProcedure.updateInvoiceQuantity(obj.getItemAmount());
				
			}
		}
		//采购发票
		if(obj.getBillType().equals("CGFP")){
			if ((obj.getOrigin().equals("CGRK") 
					|| obj.getOrigin().equals("CGCK")
					|| obj.getOrigin().equals("WWRK") 
					|| obj.getOrigin().equals("WWCK")
					|| obj.getOrigin().equals("GYZY")
					|| obj.getOrigin().equals("GYRK")
					|| obj.getOrigin().equals("GYCK")
					|| obj.getOrigin().equals("YCWG")
					) && Utils.isNotEmptyString(obj.getOriginNo()) && Utils.isNotEmptyString(obj.getOriginSerialNo())){
				//如果数据来源是采购进货单，则更新正在开票数量
				//插入
				storageRecordDetailService.updateInvoiceItemQuantityIng(obj.getOriginNo(),obj.getOriginSerialNo(), obj.getEnterpriseNo(),obj.getItemAmount());
			}
		}
		//三、暂估成本
		if(obj.getBillType().equals("ZGCB")){
			//更新采购进货单单的暂估数量和暂估金额
			if ((obj.getOrigin().equals("CGRK") 
					|| obj.getOrigin().equals("CGCK")
					|| obj.getOrigin().equals("WWRK") 
					|| obj.getOrigin().equals("WWCK")
					) && Utils.isNotEmptyString(obj.getOriginNo()) && Utils.isNotEmptyString(obj.getOriginSerialNo())){

				storageRecordDetailService.updateEvaluateItemQuantityIng(obj.getOriginNo(), obj.getOriginSerialNo(), obj.getEnterpriseNo(), obj.getItemAmount());
			}
		}

		
	}
	
	@Transactional
	@Override
    public void beforeDeleteInvoiceDetail(String fID){
		AccountInvoiceDetail obj = accountInvoiceDetailService.getByID(fID);

		//更新主表合计
		//删除
		//销售发票
		if(obj.getBillType().equals("XSFP")){
			
			if ((obj.getOrigin().equals("XSCK") 
					|| obj.getOrigin().equals("XSRK")
//					|| obj.getOrigin().equals("WXFL")
//					|| obj.getOrigin().equals("WXTL")
//					|| obj.getOrigin().equals("XCFL")
//					|| obj.getOrigin().equals("XCTL")
					) && Utils.isNotEmptyString(obj.getOriginNo()) && Utils.isNotEmptyString(obj.getOriginSerialNo())){

				//如果数据来源是销售发货单，则更新正在开票数量
				//删除
				storageRecordDetailService.updateInvoiceItemQuantityIng(obj.getOriginNo(),obj.getOriginSerialNo(), obj.getEnterpriseNo(),obj.getItemAmount().negate());
			}
			if (obj.getOrigin().equals("WXDJ") 
					|| obj.getOrigin().equals("YCWX")
					|| obj.getOrigin().equals("XCWX")
					){
				//如果数据来源是销售发货单，则更新正在开票数量
				//插入
				/*
				RepairProcedure repairProcedure= new RepairProcedure(obj.getOriginNo(), obj.getEnterpriseNo());
				iReturn=repairProcedure.updateInvoiceQuantity(obj.getItemAmount().negate());
				*/
			}
		}
		//采购发票
		if(obj.getBillType().equals("CGFP")){
			if ((obj.getOrigin().equals("CGRK") 
					|| obj.getOrigin().equals("CGCK")
					|| obj.getOrigin().equals("WWRK") 
					|| obj.getOrigin().equals("WWCK")
					|| obj.getOrigin().equals("GYZY")
					|| obj.getOrigin().equals("GYRK")
					|| obj.getOrigin().equals("GYCK")
					|| obj.getOrigin().equals("YCWG")
					) && Utils.isNotEmptyString(obj.getOriginNo()) && Utils.isNotEmptyString(obj.getOriginSerialNo())){
				//如果数据来源是采购进货单，则更新正在开票数量
				//插入
				storageRecordDetailService.updateInvoiceItemQuantityIng(obj.getOriginNo(),obj.getOriginSerialNo(), obj.getEnterpriseNo(),obj.getItemAmount().negate());
			}
		}
		//三、暂估成本
		if(obj.getBillType().equals("ZGCB")){
			//更新采购进货单单的暂估数量和暂估金额
			if ((obj.getOrigin().equals("CGRK") 
					|| obj.getOrigin().equals("CGCK")
					|| obj.getOrigin().equals("WWRK") 
					|| obj.getOrigin().equals("WWCK")
					) && Utils.isNotEmptyString(obj.getOriginNo()) && Utils.isNotEmptyString(obj.getOriginSerialNo())){

				storageRecordDetailService.updateEvaluateItemQuantityIng(obj.getOriginNo(), obj.getOriginSerialNo(), obj.getEnterpriseNo(), obj.getItemAmount().negate());
			}
		}
		
	}



	
	@Transactional
	@Override
	public Map<String,Object> accountInvoiceConfirm(String rowID, String tUsercode, String tUsername, String userId, String employeeNo, String employeeName){
		AccountInvoice obj = accountInvoiceService.getByID(rowID);
		
//		List<AccountInvoiceDetail> objs = accountInvoiceDetailService.getByMasterID(rowID);
		
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getAccountInvoiceNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);

		//首先审核从表
		int rtn = accountInvoiceDetailService.confirmByMasterID(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode("100001");
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo("从表提交失败！");
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		//然后审核主表
		rtn = accountInvoiceService.confirm(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode("100001");
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo("主表提交失败！");
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		//自动审核
		if(accountInvoiceService.getByID(rowID).getFlowType()==0){
			//审核
			Map<String,Object> map = this.accountInvoiceAgreeIt(rowID, tUsercode, tUsername, userId, employeeNo, employeeName);
			mapMessage.fromMap(map);
			//检查结果是否包括失败状态，如果包括，直接返回
			if (mapMessage.getStatusFlag().equals(MapMessage.STATUSINFO_FAILURE_FLAG)){
				return mapMessage.toMap();
			}
			
		}
		
		
		return mapMessage.toMap();
	}

	@Transactional
	@Override
	public Map<String,Object> accountInvoiceActive(String rowID){
		AccountInvoice obj = accountInvoiceService.getByID(rowID);
		
//		List<AccountInvoiceDetail> objs = accountInvoiceDetailService.getByMasterID(rowID);
		
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getAccountInvoiceNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);

		//首先审核从表
		int rtn = accountInvoiceDetailService.activeByMasterID(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode("100001");
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo("从表撤销提交失败！");
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		//然后审核主表
		rtn = accountInvoiceService.active(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode("100001");
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo("主表撤销提交失败！");
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		return mapMessage.toMap();
	}


	//审核出入库单（改造为主从表不关联审核）
	@Transactional
	@Override
	public Map<String,Object> accountInvoiceAgreeIt(String rowID, String tUsercode, String tUsername, String userId, String employeeNo, String employeeName){
		AccountInvoice accountInvoice = accountInvoiceService.getByID(rowID);
		
//		List<AccountInvoiceDetail> objs = accountInvoiceDetailService.getByMasterID(rowID);
		
		MapMessage mapMessage = new MapMessage(accountInvoice.getfID(),accountInvoice.getAccountInvoiceNo(),accountInvoice.getBillType(),accountInvoice.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		
		
//		accountInvoiceDetailService.agreeItByMasterID(rowID);
		List<AccountInvoiceDetail> accountInvoiceDetails = accountInvoiceDetailService.getByMasterID(rowID);
		for(AccountInvoiceDetail accountInvoiceDetail : accountInvoiceDetails){
			accountInvoiceDetailService.agreeIt(accountInvoiceDetail);
			this.doItInvoiceDetail(accountInvoiceDetail);
		}
		
		//然后审核主表
		accountInvoiceService.agreeIt(accountInvoice, tUsercode, tUsername, userId);
		
		this.doItInvoice(accountInvoice);
		
		
		/*
		//销售发票现结处理（删除），插入放在前台销售发票审核完毕之后处理
		if("Y".equals(obj.getAutoPayment()) && "XSFP".equals(obj.getBillType()) && obj.getDirection()==1){
			//生成收款单
			
			String autoState = "N";
			String flowType = "0";//自动审核
			String autoPayment = "Y";//现结
			
			AccountInvoice accountPayment = accountPaymentService.accountPaymentSKDJInsert(obj, null, tUsercode, tUsername, userId, autoState, flowType, autoPayment, employeeNo, employeeName);
			Map<String,Object> map = this.accountPaymentConfirm(accountPayment.getfID(), tUsercode, tUsername, userId, employeeNo, employeeName);
			mapMessage.fromMap(map);
			//测试data属性
			JSONObject json = new JSONObject();
			json.put("xjskdh", accountPayment.getAccountInvoiceNo());
			mapMessage.setData(json);
		}
		*/
		
		
		//销售发票审核完成后，如果存在相关客户订单预付款单，则自动核销
		//主要针对客户网上订单付款的情况
		/*
		String orderNo = accountInvoice.getOrderNo();
		String enterpriseNo = accountInvoice.getEnterpriseNo();
		String enterpriseName = accountInvoice.getEnterpriseName();
		AccountInvoice accountPayment = accountPaymentService.getYSKDByOriginNo(orderNo, enterpriseNo);
		if(accountPayment!=null) {
			//存在，判断金额是否相等（包含发票中存在折扣金额的情况）
			if(accountInvoice.getOrderAmountTotal().subtract(accountInvoice.getDiscountAmount()).compareTo(accountPayment.getOrderAmountTotal())==0) {
				this.accountInvoiceHXself(accountInvoice, tUsercode, tUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
			}
		}
		*/

		
		return mapMessage.toMap();

	}

	@Transactional
	@Override
	public Map<String,Object> accountInvoiceUnAgree(String rowID){
		AccountInvoice accountInvoice = accountInvoiceService.getByID(rowID);
		
//		List<AccountInvoiceDetail> objs = accountInvoiceDetailService.getByMasterID(rowID);
		
		MapMessage mapMessage = new MapMessage(accountInvoice.getfID(),accountInvoice.getAccountInvoiceNo(),accountInvoice.getBillType(),accountInvoice.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		
		/*
		//销售发票现结处理（删除），插入放在前台销售发票审核完毕之后处理
		if("Y".equals(obj.getAutoPayment()) && "XSFP".equals(obj.getBillType()) && obj.getDirection()==1){
			//删除现结收款单
			String accountPaymentNo = obj.getNextNo();
			String enterpriseNo = obj.getEnterpriseNo();
			AccountInvoice accountPayment = accountPaymentService.getSKDJByNo(accountPaymentNo, enterpriseNo);
			if(accountPayment!=null){
				String fID = accountPayment.getfID();
//				accountPaymentService.unAgreeByMasterID(fID);
//				accountPaymentService.unAgree(fID);
//				accountPaymentService.deleteByMasterID(fID);
//				accountPaymentService.delete(fID);
				this.accountPaymentUnAgree(fID);
				this.accountPaymentActive(fID);
				this.accountPaymentDelete(fID);
			}
			
		}
		*/

		//首先审核子表
//		accountInvoiceDetailService.unAgreeByMasterID(rowID);
		List<AccountInvoiceDetail> accountInvoiceDetails = accountInvoiceDetailService.getByMasterID(rowID);
		for(AccountInvoiceDetail accountInvoiceDetail : accountInvoiceDetails){
			accountInvoiceDetailService.unAgree(accountInvoiceDetail);
			this.unDoInvoiceDetail(accountInvoiceDetail);
		}
		
		//然后审核主表
		accountInvoiceService.unAgree(accountInvoice);
		
		this.unDoInvoice(accountInvoice);
		
		return mapMessage.toMap();

	}

	@Transactional
	@Override
	public int accountInvoiceClose(String rowID){

		//首先审核从表
		int rtn = accountInvoiceDetailService.closeByMasterID(rowID);
		if (rtn != 0){
			return -1;
		}
		
		//然后审核主表
		rtn = accountInvoiceService.close(rowID);
		if (rtn != 0){
			return -1;
		}
		
		return 0;
	}

	@Transactional
	@Override
	public int accountInvoiceOpen(String rowID){

		//首先审核从表
		int rtn = accountInvoiceDetailService.openByMasterID(rowID);
		if (rtn != 0){
			return -1;
		}
		
		//然后审核主表
		rtn = accountInvoiceService.open(rowID);
		if (rtn != 0){
			return -1;
		}
		
		return 0;
	}
  
    
	@Override
	public void accountInvoicePrintPDF(String fID, Document doc) throws Exception {
		
//	@Test
//	public void saleOrderPrintPDF() throws Exception {
//		log.info("fID-->"+id);
		
//	    Document doc = new Document();// 创建一个PDF文档，我们的PDF内容都写在上面
	    
//	    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File("c://pdftest//saleOrder.pdf"))); // 将pdf文档写入文件

//		String fID = "bf61ec2bc8163a3ad3d8572ad2fee7c6";
		AccountInvoice accountInvoice = accountInvoiceService.getByID(fID);
	   
//	    response.setContentType("application/pdf");
//	    PdfWriter.getInstance(doc, response.getOutputStream());
//	    
//	    doc.open();
	    
	    Font fontEN = new Font(BaseFont.createFont(),9);
	    BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);  	    
//	    Font font = new Font(baseFont, 10, Font.ITALIC);
	    Font fontCN = new Font(baseFont, 9);
	    Paragraph pEnterpriseName = new Paragraph(accountInvoice.getEnterpriseName(),fontCN);
	    // 居中显示
	    pEnterpriseName.setAlignment(Element.ALIGN_CENTER);
	    pEnterpriseName.setSpacingAfter(-10);
	    Paragraph pBillTypeName = new Paragraph(accountInvoice.getBillTypeName(),new Font(baseFont,20));
	    // 居中显示
	    pBillTypeName.setAlignment(Element.ALIGN_CENTER);
	    LineSeparator line = new LineSeparator(1f, 100, BaseColor.BLACK, Element.ALIGN_CENTER, -5f);

	    
	    
	    
	    
	    
	    doc.add(pEnterpriseName);
	    doc.add(pBillTypeName);
	    doc.add(line);
	    
	    
        PdfPTable masterHead = new PdfPTable(8);
        
//        masterHead.setTotalWidth(new float[]{60, 200, 60, 200});
        masterHead.setTotalWidth(new float[]{45, 85, 45, 85, 45, 85, 45, 85});
        masterHead.setLockedWidth(true);
        masterHead.setSpacingBefore(10);
        
        PdfPCell ordrDateCell = new PdfPCell(new Phrase("单据日期:", fontCN));
        ordrDateCell.setUseBorderPadding(true);
        //
        // Setting cell's border width and color
        //
        ordrDateCell.setBorderWidth(0f);
//        ordrDateCell.setBorderColor(BaseColor.BLUE);
        masterHead.addCell(ordrDateCell);

        PdfPCell ordrDateValue = new PdfPCell(new Phrase(accountInvoice.getOrderDate().toString(), fontEN));
        ordrDateValue.setUseBorderPadding(true);
        ordrDateValue.setBorderWidth(0f);
        //
        // Setting cell's background color
        //
//        cell2.setBackgroundColor(BaseColor.GRAY);
        //
        // Setting cell's individual border color
        //
//        cell2.setBorderWidthTop(1f);
//        cell2.setBorderColorTop(BaseColor.RED);
//        cell2.setBorderColorRight(BaseColor.GREEN);
//        cell2.setBorderColorBottom(BaseColor.BLUE);
//        cell2.setBorderColorLeft(BaseColor.BLACK);
        masterHead.addCell(ordrDateValue);

        PdfPCell auditCell = new PdfPCell(new Phrase("单据状态:", fontCN));
        auditCell.setUseBorderPadding(true);
        auditCell.setBorderWidth(0f);
        //
        // Setting cell's individual border width
        //
//        cell3.setBorderWidthTop(2f);
//        cell3.setBorderWidthRight(1f);
//        cell3.setBorderWidthBottom(2f);
//        cell3.setBorderWidthLeft(1f);
        masterHead.addCell(auditCell);

        String auditStatus = "待审核";
        String audit = accountInvoice.getAudit();
        String state = accountInvoice.getState();
        if(audit.equals("confirm")){
        	auditStatus = "已审核";
        }else if(audit.equals("active") && state.equals("confirm")){
        	auditStatus = "审核中";
        }else{
        	auditStatus = "待审核";
        }
        
       PdfPCell auditValue = new PdfPCell(new Phrase(auditStatus, fontCN));
       auditValue.setUseBorderPadding(true);
       auditValue.setBorderWidth(0f);
        //
        // Setting cell's individual border width
        //
//        cell4.setBorderWidthTop(2f);
//        cell4.setBorderWidthRight(1f);
//        cell4.setBorderWidthBottom(2f);
//        cell4.setBorderWidthLeft(1f);
        masterHead.addCell(auditValue);
        
        PdfPCell customerNoCell = new PdfPCell(new Phrase("对象编码:", fontCN));
        customerNoCell.setBorder(0);
        masterHead.addCell(customerNoCell);
        PdfPCell customerNoValue = new PdfPCell(new Phrase(accountInvoice.getCustomerNo(), fontEN));
        customerNoValue.setBorder(0);
        masterHead.addCell(customerNoValue);
        
        PdfPCell shortNameCell = new PdfPCell(new Phrase("对象简称:", fontCN));
        shortNameCell.setBorder(0);
        masterHead.addCell(shortNameCell);
        PdfPCell shortNameValue = new PdfPCell(new Phrase(accountInvoice.getShortName(), fontCN));
        shortNameValue.setBorder(0);
        masterHead.addCell(shortNameValue);

        //第一行结束
        masterHead.completeRow();
        
        PdfPCell orderNoCell = new PdfPCell(new PdfPCell(new Phrase("单号:", fontCN)));
        orderNoCell.setBorder(0);
        masterHead.addCell(orderNoCell);
        PdfPCell orderNoValue = new PdfPCell(new PdfPCell(new Phrase(accountInvoice.getAccountInvoiceNo(), fontEN)));
        orderNoValue.setBorder(0);
        masterHead.addCell(orderNoValue);
        
        PdfPCell discountRateMCell = new PdfPCell(new PdfPCell(new Phrase("折扣率:", fontCN)));
        discountRateMCell.setBorder(0);
        masterHead.addCell(discountRateMCell);
        String discountRate = accountInvoice.getDiscountRate().multiply(new BigDecimal(100)).toString() + "%";
        PdfPCell discountRateMValue = new PdfPCell(new PdfPCell(new Phrase(discountRate, fontEN)));
        discountRateMValue.setBorder(0);
        masterHead.addCell(discountRateMValue);
        
        PdfPCell customerNameCell = new PdfPCell(new Phrase("交易对象:", fontCN));
        customerNameCell.setBorder(0);
        masterHead.addCell(customerNameCell);
        PdfPCell customerNameValue = new PdfPCell(new Phrase(accountInvoice.getCustomerName(), fontCN));
        customerNameValue.setBorder(0);
        customerNameValue.setColspan(3);
        masterHead.addCell(customerNameValue);
        //第二行结束
        masterHead.completeRow();
        
        PdfPCell factoryNoCell = new PdfPCell(new PdfPCell(new Phrase("门店编码:", fontCN)));
        factoryNoCell.setBorder(0);
        masterHead.addCell(factoryNoCell);
        PdfPCell factoryNoValue = new PdfPCell(new PdfPCell(new Phrase("", fontEN)));
        factoryNoValue.setBorder(0);
        masterHead.addCell(factoryNoValue);
        
        PdfPCell factoryNameCell = new PdfPCell(new PdfPCell(new Phrase("门店名称:", fontCN)));
        factoryNameCell.setBorder(0);
        masterHead.addCell(factoryNameCell);
        PdfPCell factoryNameValue = new PdfPCell(new PdfPCell(new Phrase("", fontCN)));
        factoryNameValue.setBorder(0);
        masterHead.addCell(factoryNameValue);
        
        PdfPCell invoiceCategoryLabelCell = new PdfPCell(new PdfPCell(new Phrase("发票类型:", fontCN)));
        invoiceCategoryLabelCell.setBorder(0);
        masterHead.addCell(invoiceCategoryLabelCell);
        PdfPCell invoiceCategoryLabelValue = new PdfPCell(new PdfPCell(new Phrase(accountInvoice.getInvoiceCategoryLabel(), fontCN)));
        invoiceCategoryLabelValue.setBorder(0);
        masterHead.addCell(invoiceCategoryLabelValue);
        
        PdfPCell settleCategoryLabelCell = new PdfPCell(new Phrase("结算方式:", fontCN));
        settleCategoryLabelCell.setBorder(0);
        masterHead.addCell(settleCategoryLabelCell);
        PdfPCell settleCategoryLabelValue = new PdfPCell(new Phrase(accountInvoice.getSettleCategoryLabel(), fontCN));
        settleCategoryLabelValue.setBorder(0);
        masterHead.addCell(settleCategoryLabelValue);
        //第三行结束
        masterHead.completeRow();
        
        PdfPCell taxTypeLabelCell = new PdfPCell(new PdfPCell(new Phrase("税种:", fontCN)));
        taxTypeLabelCell.setBorder(0);
        masterHead.addCell(taxTypeLabelCell);
        PdfPCell taxTypeLabelValue = new PdfPCell(new PdfPCell(new Phrase(accountInvoice.getTaxTypeLabel(), fontCN)));
        taxTypeLabelValue.setBorder(0);
        masterHead.addCell(taxTypeLabelValue);
        
        PdfPCell taxRateCell = new PdfPCell(new PdfPCell(new Phrase("税率:", fontCN)));
        taxRateCell.setBorder(0);
        masterHead.addCell(taxRateCell);
        PdfPCell taxRateValue = new PdfPCell(new PdfPCell(new Phrase(accountInvoice.getTaxRate().toString(), fontEN)));
        taxRateValue.setBorder(0);
        masterHead.addCell(taxRateValue);
        
        PdfPCell accountBankCell = new PdfPCell(new PdfPCell(new Phrase("开户银行:", fontCN)));
        accountBankCell.setBorder(0);
        masterHead.addCell(accountBankCell);
        PdfPCell accountBankValue = new PdfPCell(new PdfPCell(new Phrase(accountInvoice.getAccountBank(), fontCN)));
        accountBankValue.setBorder(0);
        accountBankValue.setColspan(3);
        masterHead.addCell(accountBankValue);
        //第四行结束
        masterHead.completeRow();
        
        PdfPCell employeeNameCell = new PdfPCell(new Phrase("经办人:", fontCN));
        employeeNameCell.setBorder(0);
        masterHead.addCell(employeeNameCell);
        PdfPCell employeeNameValue = new PdfPCell(new Phrase(accountInvoice.getEmployeeName(), fontCN));
        employeeNameValue.setBorder(0);
        employeeNameValue.setColspan(3);
        masterHead.addCell(employeeNameValue);
        
        PdfPCell accountNoCell = new PdfPCell(new PdfPCell(new Phrase("银行账号:", fontCN)));
        accountNoCell.setBorder(0);
        masterHead.addCell(accountNoCell);
        PdfPCell accountNoValue = new PdfPCell(new PdfPCell(new Phrase(accountInvoice.getAccountNo(), fontEN)));
        accountNoValue.setBorder(0);
        accountNoValue.setColspan(3);
        masterHead.addCell(accountNoValue);

        //第五行结束
        masterHead.completeRow();
        
        PdfPCell invoiceCodeCell = new PdfPCell(new Phrase("发票号码:", fontCN));
        invoiceCodeCell.setBorder(0);
        masterHead.addCell(invoiceCodeCell);
        PdfPCell invoiceCodeValue = new PdfPCell(new Phrase(accountInvoice.getInvoiceCode(), fontCN));
        invoiceCodeValue.setBorder(0);
        masterHead.addCell(invoiceCodeValue);
        
        PdfPCell invoiceDateCell = new PdfPCell(new Phrase("发票日期:", fontCN));
        invoiceDateCell.setBorder(0);
        masterHead.addCell(invoiceDateCell);
        PdfPCell invoiceDateValue = new PdfPCell(new Phrase(accountInvoice.getInvoiceDate()==null?null:accountInvoice.getInvoiceDate().toString(), fontEN));
        invoiceDateValue.setBorder(0);
        masterHead.addCell(invoiceDateValue);
        
        PdfPCell taxNoCell = new PdfPCell(new Phrase("税号:", fontCN));
        taxNoCell.setBorder(0);
        masterHead.addCell(taxNoCell);
        PdfPCell taxNoValue = new PdfPCell(new Phrase(accountInvoice.getTaxNo(), fontCN));
        taxNoValue.setBorder(0);
        masterHead.addCell(taxNoValue);
        
        PdfPCell predictDateCell = new PdfPCell(new Phrase("预计付款:", fontCN));
        predictDateCell.setBorder(0);
        masterHead.addCell(predictDateCell);
        PdfPCell predictDateValue = new PdfPCell(new Phrase(accountInvoice.getPredictStart()==null?null:accountInvoice.getPredictStart().toString(), fontEN));
        predictDateValue.setBorder(0);
        masterHead.addCell(predictDateValue);
        //第六行结束
        masterHead.completeRow();
        
        PdfPCell paymentTermLabelCell = new PdfPCell(new Phrase("付款条件:", fontCN));
        paymentTermLabelCell.setBorder(0);
        masterHead.addCell(paymentTermLabelCell);
        PdfPCell paymentTermLabelValue = new PdfPCell(new Phrase(accountInvoice.getPaymentTermLabel(), fontCN));
        paymentTermLabelValue.setBorder(0);
        paymentTermLabelValue.setColspan(7);
        masterHead.addCell(paymentTermLabelValue);
        //第七行结束
        masterHead.completeRow();
        
        PdfPCell commentsCell = new PdfPCell(new Phrase("备注:", fontCN));
        commentsCell.setBorder(0);
        masterHead.addCell(commentsCell);
        PdfPCell commentsValue = new PdfPCell(new Phrase(accountInvoice.getComments(), fontCN));
        commentsValue.setBorder(0);
        commentsValue.setColspan(7);
        masterHead.addCell(commentsValue);
        
        //第n行结束
        masterHead.completeRow();

        doc.add(masterHead);
//	    doc.add(line);
	    

        /*
        Image image = Image.getInstance("c://pdftest//smp.png");

        image.setAlignment(Image.ALIGN_RIGHT);
        // 设置边框
        image.setBorder(Image.BOX);
        image.setBorderWidth(2);
        image.setBorderColor(BaseColor.RED);
        // 设置图片大小
        
//        ScaleToFit有两个参数，指的是长和宽的最大值，但是图片的长宽比还是不会变的
//        ScaleAbsoluteHeight设置图片的高度，不管长宽比 ScaleAbsoluteWidth设置图片的宽度，不管长宽比
//        ScalePercent等比例缩放
        
//         image.scaleToFit(100, 100);
//         image.scaleAbsoluteHeight(100f);
//         image.scaleAbsoluteWidth(100f);

        image.scalePercent(50f);
        // 图片旋转30度
        image.setRotationDegrees(30);

        doc.add(image);
        */
        
        
        
        
        
	    //////////////////////////////////////////////////////////////////////////////////////////
	    
        PdfPTable details = new PdfPTable(8);
        details.setTotalWidth(new float[]{15, 70, 70, 80, 65, 75, 65, 80});//520
        details.setLockedWidth(true);
        details.setSpacingBefore(10);

        PdfPCell sharpCell = new PdfPCell(new Phrase("序号", fontCN));
//        sharpCell.setBorder(0);
        sharpCell.setRowspan(4);
        sharpCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        sharpCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        details.addCell(sharpCell);

        PdfPCell itemNoCell = new PdfPCell(new Phrase("物料编码", fontCN));
//        itemNoCell.setBorder(0);
//        itemNoCell.setBorderWidthTop(0);
        itemNoCell.setBorderWidthLeft(0);
        itemNoCell.setBorderWidthBottom(0);
        itemNoCell.setBorderWidthRight(0);
        itemNoCell.setColspan(2);
        details.addCell(itemNoCell);

        PdfPCell projectNoCell = new PdfPCell(new Phrase("项目号", fontCN));
//        projectNoCell.setBorder(0);
        projectNoCell.setBorderWidthLeft(0);
        projectNoCell.setBorderWidthBottom(0);
        projectNoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(projectNoCell);

        PdfPCell requirementDateCell = new PdfPCell(new Phrase("", fontCN));
//        requirementDateCell.setBorder(0);
        requirementDateCell.setBorderWidthLeft(0);
        requirementDateCell.setBorderWidthBottom(0);
        requirementDateCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(requirementDateCell);

        PdfPCell itemAmountsCell = new PdfPCell(new Phrase("开票数量", fontCN));
//        itemAmountsCell.setBorder(0);
        itemAmountsCell.setBorderWidthLeft(0);
        itemAmountsCell.setBorderWidthBottom(0);
        itemAmountsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(itemAmountsCell);

        PdfPCell taxRatesCell = new PdfPCell(new Phrase("税率", fontCN));
//        taxRatesCell.setBorder(0);
        taxRatesCell.setBorderWidthLeft(0);
        taxRatesCell.setBorderWidthBottom(0);
        taxRatesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(taxRatesCell);

        PdfPCell commentssCell = new PdfPCell(new Phrase("备注", fontCN));
//        commentssCell.setBorder(0);
        commentssCell.setBorderWidthLeft(0);
        commentssCell.setRowspan(4);
        details.addCell(commentssCell);
        
        details.completeRow();
        //第一行结束

        PdfPCell itemDescribeCell = new PdfPCell(new Phrase("名称", fontCN));
//        itemDescribeCell.setBorder(0);
        itemDescribeCell.setBorderWidthTop(0);
        itemDescribeCell.setBorderWidthLeft(0);
        itemDescribeCell.setBorderWidthBottom(0);
        itemDescribeCell.setColspan(3);
        details.addCell(itemDescribeCell);

        PdfPCell taxTypeLabelsCell = new PdfPCell(new Phrase("税种", fontCN));
//        taxTypeLabelsCell.setBorder(0);
        taxTypeLabelsCell.setBorderWidthTop(0);
        taxTypeLabelsCell.setBorderWidthLeft(0);
        taxTypeLabelsCell.setBorderWidthBottom(0);
        taxTypeLabelsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(taxTypeLabelsCell);

        PdfPCell pickItemAmountsCell = new PdfPCell(new Phrase("", fontCN));
//        pickItemAmountsCell.setBorder(0);
        pickItemAmountsCell.setBorderWidthTop(0);
        pickItemAmountsCell.setBorderWidthLeft(0);
        pickItemAmountsCell.setBorderWidthBottom(0);
        pickItemAmountsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(pickItemAmountsCell);

        PdfPCell orderAmountOldsCell = new PdfPCell(new Phrase("未税金额", fontCN));
//        orderAmountOldsCell.setBorder(0);
        orderAmountOldsCell.setBorderWidthTop(0);
        orderAmountOldsCell.setBorderWidthLeft(0);
        orderAmountOldsCell.setBorderWidthBottom(0);
        orderAmountOldsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountOldsCell);

        details.completeRow();
        //第二行结束

        PdfPCell itemPropertyCell = new PdfPCell(new Phrase("规格", fontCN));
//        itemPropertyCell.setBorder(0);
        itemPropertyCell.setBorderWidthTop(0);
        itemPropertyCell.setBorderWidthLeft(0);
        itemPropertyCell.setBorderWidthBottom(0);
        itemPropertyCell.setBorderWidthRight(0);
        itemPropertyCell.setColspan(2);
        details.addCell(itemPropertyCell);

        PdfPCell unitNameCell = new PdfPCell(new Phrase("单位", fontCN));
//        unitNameCell.setBorder(0);
        unitNameCell.setBorderWidthTop(0);
        unitNameCell.setBorderWidthLeft(0);
        unitNameCell.setBorderWidthBottom(0);
        unitNameCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(unitNameCell);

        PdfPCell discountRateCell = new PdfPCell(new Phrase("折扣率", fontCN));
//        discountRateCell.setBorder(0);
        discountRateCell.setBorderWidthTop(0);
        discountRateCell.setBorderWidthLeft(0);
        discountRateCell.setBorderWidthBottom(0);
        discountRateCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(discountRateCell);

        PdfPCell itemPriceCell = new PdfPCell(new Phrase("开票单价", fontCN));
//        itemPriceCell.setBorder(0);
        itemPriceCell.setBorderWidthTop(0);
        itemPriceCell.setBorderWidthLeft(0);
        itemPriceCell.setBorderWidthBottom(0);
        itemPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(itemPriceCell);

        PdfPCell orderAmountTaxsCell = new PdfPCell(new Phrase("税额", fontCN));
//        orderAmountTaxsCell.setBorder(0);
        orderAmountTaxsCell.setBorderWidthTop(0);
        orderAmountTaxsCell.setBorderWidthLeft(0);
        orderAmountTaxsCell.setBorderWidthBottom(0);
        orderAmountTaxsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountTaxsCell);

        details.completeRow();
        //第三行结束

        PdfPCell floorNoCell = new PdfPCell(new Phrase("来源单号", fontCN));
//        floorNoCell.setBorder(0);
        floorNoCell.setBorderWidthTop(0);
        floorNoCell.setBorderWidthLeft(0);
        floorNoCell.setBorderWidthRight(0);
        floorNoCell.setColspan(2);
        details.addCell(floorNoCell);

        PdfPCell storageNoCell = new PdfPCell(new Phrase("来源", fontCN));
//        storageNoCell.setBorder(0);
        storageNoCell.setBorderWidthTop(0);
        storageNoCell.setBorderWidthLeft(0);
        storageNoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(storageNoCell);

        PdfPCell emptyCell = new PdfPCell(new Phrase("", fontCN));
//        emptyCell.setBorder(0);
        emptyCell.setBorderWidthTop(0);
        emptyCell.setBorderWidthLeft(0);
        emptyCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(emptyCell);

        PdfPCell orderAmountCell = new PdfPCell(new Phrase("金额", fontCN));
//        orderAmountCell.setBorder(0);
        orderAmountCell.setBorderWidthTop(0);
        orderAmountCell.setBorderWidthLeft(0);
        orderAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountCell);

        PdfPCell orderAmountTotalsCell = new PdfPCell(new Phrase("价税合计", fontCN));
//        orderAmountTotalsCell.setBorder(0);
        orderAmountTotalsCell.setBorderWidthTop(0);
        orderAmountTotalsCell.setBorderWidthLeft(0);
        orderAmountTotalsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountTotalsCell);

        details.completeRow();
        //第四行结束
        
        
//        doc.add(details);
        
        ////////////////////////////////////////////////////////////////////////////////////////////
        
        
	    //////////////////////////////////////////////////////////////////////////////////////////
        List<AccountInvoiceDetail> accountInvoiceDetails = accountInvoiceDetailService.getByMasterID(fID);
        if(accountInvoiceDetails.size()>0){
    	    
//            PdfPTable detailsValue = new PdfPTable(8);
//            
//            detailsValue.setTotalWidth(new float[]{20, 70, 70, 80, 80, 80, 60, 60});//520
//            detailsValue.setLockedWidth(true);
//            detailsValue.setSpacingBefore(10);
            
            for(int i=0;i<accountInvoiceDetails.size();i++){
            	AccountInvoiceDetail accountInvoiceDetail = accountInvoiceDetails.get(i);

            	//序号
            	String rowNo = String.valueOf(i+1);
                PdfPCell sharpValue = new PdfPCell(new Phrase(rowNo, fontEN));
//                sharpValue.setBorder(0);
                sharpValue.setBorderWidthTop(0);
                sharpValue.setRowspan(4);
                sharpValue.setHorizontalAlignment(Element.ALIGN_CENTER);
                sharpValue.setVerticalAlignment(Element.ALIGN_MIDDLE);
                details.addCell(sharpValue);

                PdfPCell itemNoValue = new PdfPCell(new Phrase(accountInvoiceDetail.getItemNo(), fontEN));
//                itemNoValue.setBorder(0);
                itemNoValue.setBorderWidthTop(0);
                itemNoValue.setBorderWidthLeft(0);
                itemNoValue.setBorderWidthBottom(0);
                itemNoValue.setBorderWidthRight(0);
                itemNoValue.setColspan(2);
                details.addCell(itemNoValue);

                PdfPCell projectNoValue = new PdfPCell(new Phrase(accountInvoiceDetail.getProjectNo(), fontEN));
//                projectNoValue.setBorder(0);
                projectNoValue.setBorderWidthTop(0);
                projectNoValue.setBorderWidthLeft(0);
                projectNoValue.setBorderWidthBottom(0);
                projectNoValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(projectNoValue);

                PdfPCell requirementDateValue = new PdfPCell(new Phrase("", fontEN));
//                requirementDateValue.setBorder(0);
                requirementDateValue.setBorderWidthTop(0);
                requirementDateValue.setBorderWidthLeft(0);
                requirementDateValue.setBorderWidthBottom(0);
                requirementDateValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(requirementDateValue);

                PdfPCell itemAmountValue = new PdfPCell(new Phrase(accountInvoiceDetail.getItemAmount().toString(), fontEN));
//                itemAmountValue.setBorder(0);
                itemAmountValue.setBorderWidthTop(0);
                itemAmountValue.setBorderWidthLeft(0);
                itemAmountValue.setBorderWidthBottom(0);
                itemAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(itemAmountValue);

                PdfPCell taxRatesValue = new PdfPCell(new Phrase(accountInvoiceDetail.getTaxRate().toString(), fontEN));
//                taxRatesValue.setBorder(0);
                taxRatesValue.setBorderWidthTop(0);
                taxRatesValue.setBorderWidthLeft(0);
                taxRatesValue.setBorderWidthBottom(0);
                taxRatesValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(taxRatesValue);

                PdfPCell commentssValue = new PdfPCell(new Phrase(accountInvoiceDetail.getComments(), fontCN));
//                commentssValue.setBorder(0);
                commentssValue.setBorderWidthTop(0);
                commentssValue.setBorderWidthLeft(0);
                commentssValue.setRowspan(4);
                details.addCell(commentssValue);
                
                details.completeRow();
                //第一行结束
 
                PdfPCell itemDescribeValue = new PdfPCell(new Phrase(accountInvoiceDetail.getItemName(), fontCN));
//              itemDescribeValue.setBorder(0);
                itemDescribeValue.setBorderWidthTop(0);
                itemDescribeValue.setBorderWidthLeft(0);
                itemDescribeValue.setBorderWidthBottom(0);
                itemDescribeValue.setColspan(3);
              details.addCell(itemDescribeValue);

              PdfPCell taxTypeLabelsValue = new PdfPCell(new Phrase(accountInvoiceDetail.getTaxTypeLabel(), fontCN));
//              taxTypeLabelsValue.setBorder(0);
              taxTypeLabelsValue.setBorderWidthTop(0);
              taxTypeLabelsValue.setBorderWidthLeft(0);
              taxTypeLabelsValue.setBorderWidthBottom(0);
              taxTypeLabelsValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(taxTypeLabelsValue);


              PdfPCell pickItemAmountValue = new PdfPCell(new Phrase("", fontEN));
//              pickItemAmountValue.setBorder(0);
              pickItemAmountValue.setBorderWidthTop(0);
              pickItemAmountValue.setBorderWidthLeft(0);
              pickItemAmountValue.setBorderWidthBottom(0);
              pickItemAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(pickItemAmountValue);

              PdfPCell orderAmountOldsValue = new PdfPCell(new Phrase(accountInvoiceDetail.getOrderAmountOld().toString(), fontEN));
//              orderAmountOldsValue.setBorder(0);
              orderAmountOldsValue.setBorderWidthTop(0);
              orderAmountOldsValue.setBorderWidthLeft(0);
              orderAmountOldsValue.setBorderWidthBottom(0);
              orderAmountOldsValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountOldsValue);

              details.completeRow();
              //第二行结束

              PdfPCell itemPropertyValue = new PdfPCell(new Phrase(accountInvoiceDetail.getItemProperty(), fontCN));
//              itemPropertyValue.setBorder(0);
              itemPropertyValue.setBorderWidthTop(0);
              itemPropertyValue.setBorderWidthLeft(0);
              itemPropertyValue.setBorderWidthBottom(0);
              itemPropertyValue.setBorderWidthRight(0);
              itemPropertyValue.setColspan(2);
              details.addCell(itemPropertyValue);

              PdfPCell unitNameValue = new PdfPCell(new Phrase(accountInvoiceDetail.getUnitName(), fontCN));
//              unitNameValue.setBorder(0);
              unitNameValue.setBorderWidthTop(0);
              unitNameValue.setBorderWidthLeft(0);
              unitNameValue.setBorderWidthBottom(0);
              unitNameValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(unitNameValue);

              String discountRates = accountInvoiceDetail.getDiscountRate().multiply(new BigDecimal(100)).toString() + "%";
              PdfPCell discountRateValue = new PdfPCell(new Phrase(discountRates, fontEN));
//              discountRateValue.setBorder(0);
              discountRateValue.setBorderWidthTop(0);
              discountRateValue.setBorderWidthLeft(0);
              discountRateValue.setBorderWidthBottom(0);
              discountRateValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(discountRateValue);

              PdfPCell itemPriceValue = new PdfPCell(new Phrase(accountInvoiceDetail.getItemPrice().toString(), fontEN));
//              itemPriceValue.setBorder(0);
              itemPriceValue.setBorderWidthTop(0);
              itemPriceValue.setBorderWidthLeft(0);
              itemPriceValue.setBorderWidthBottom(0);
              itemPriceValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(itemPriceValue);

              PdfPCell orderAmountTaxValue = new PdfPCell(new Phrase(accountInvoiceDetail.getOrderAmountTax().toString(), fontEN));
//              orderAmountTaxValue.setBorder(0);
              orderAmountTaxValue.setBorderWidthTop(0);
              orderAmountTaxValue.setBorderWidthLeft(0);
              orderAmountTaxValue.setBorderWidthBottom(0);
              orderAmountTaxValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountTaxValue);

              details.completeRow();
              //第三行结束
              

              PdfPCell floorNoValue = new PdfPCell(new Phrase(accountInvoiceDetail.getOriginNo(), fontCN));
//              floorNoValue.setBorder(0);
              floorNoValue.setBorderWidthTop(0);
              floorNoValue.setBorderWidthLeft(0);
              floorNoValue.setBorderWidthRight(0);
              floorNoValue.setColspan(2);
              details.addCell(floorNoValue);

              PdfPCell storageNoValue = new PdfPCell(new Phrase(accountInvoiceDetail.getOriginName(), fontCN));
//              storageNoValue.setBorder(0);
              storageNoValue.setBorderWidthTop(0);
              storageNoValue.setBorderWidthLeft(0);
              storageNoValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(storageNoValue);

              PdfPCell emptyValue = new PdfPCell(new Phrase("", fontCN));
//              emptyValue.setBorder(0);
              emptyValue.setBorderWidthTop(0);
              emptyValue.setBorderWidthLeft(0);
              emptyValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(emptyValue);

              PdfPCell orderAmountValue = new PdfPCell(new Phrase(accountInvoiceDetail.getOrderAmount().toString(), fontEN));
//              orderAmountValue.setBorder(0);
              orderAmountValue.setBorderWidthTop(0);
              orderAmountValue.setBorderWidthLeft(0);
              orderAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountValue);

              PdfPCell orderAmountTotalValue = new PdfPCell(new Phrase(accountInvoiceDetail.getOrderAmountTotal().toString(), fontEN));
//              orderAmountTotalValue.setBorder(0);
              orderAmountTotalValue.setBorderWidthTop(0);
              orderAmountTotalValue.setBorderWidthLeft(0);
              orderAmountTotalValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountTotalValue);

              details.completeRow();
              //第四行结束
              
            }
            
            doc.add(details);
            
//    	    doc.add(line);

    	    
            
            
            PdfPTable masterFoot = new PdfPTable(8);
            
            masterFoot.setTotalWidth(new float[]{45, 85, 45, 85, 45, 85, 45, 85});
            masterFoot.setLockedWidth(true);
//            masterFoot.setSpacingBefore(10);

            PdfPCell detailsCountCell = new PdfPCell(new Phrase("笔数:", fontCN));
//            detailsCountCell.setBorder(0);
            detailsCountCell.setBorderWidthTop(0);
            detailsCountCell.setBorderWidthBottom(0);
            detailsCountCell.setBorderWidthRight(0);
            masterFoot.addCell(detailsCountCell);

            PdfPCell detailsCountValue = new PdfPCell(new Phrase(String.valueOf(accountInvoice.getDetailsCount()), fontEN));
            detailsCountValue.setBorder(0);
            masterFoot.addCell(detailsCountValue);

            PdfPCell r1emptyCell = new PdfPCell(new Phrase(""));
//            r1emptyCell.setBorder(0);
            r1emptyCell.setBorderWidthTop(0);
            r1emptyCell.setBorderWidthBottom(0);
            r1emptyCell.setBorderWidthLeft(0);
            r1emptyCell.setColspan(6);
            masterFoot.addCell(r1emptyCell);

            //第一行结束
            masterFoot.completeRow();

            PdfPCell itemAmountCell = new PdfPCell(new Phrase("数量合计:", fontCN));
//            itemAmountCell.setBorder(0);
            itemAmountCell.setBorderWidthTop(0);
            itemAmountCell.setBorderWidthRight(0);
            masterFoot.addCell(itemAmountCell);

            PdfPCell itemAmountValue = new PdfPCell(new Phrase(accountInvoice.getItemAmount().toString(), fontEN));
            itemAmountValue.setBorderWidthLeft(0);
            itemAmountValue.setBorderWidthTop(0);
            itemAmountValue.setBorderWidthRight(0);
            masterFoot.addCell(itemAmountValue);

            PdfPCell orderAmountOldCell = new PdfPCell(new Phrase("未税金额:", fontCN));
            orderAmountOldCell.setBorderWidthLeft(0);
            orderAmountOldCell.setBorderWidthTop(0);
            orderAmountOldCell.setBorderWidthRight(0);
            masterFoot.addCell(orderAmountOldCell);

            PdfPCell orderAmountOldValue = new PdfPCell(new Phrase(accountInvoice.getOrderAmountOld().toString(), fontEN));
            orderAmountOldValue.setBorderWidthLeft(0);
            orderAmountOldValue.setBorderWidthTop(0);
            orderAmountOldValue.setBorderWidthRight(0);
            masterFoot.addCell(orderAmountOldValue);

            PdfPCell orderAmountTaxCell = new PdfPCell(new Phrase("税额:", fontCN));
            orderAmountTaxCell.setBorderWidthLeft(0);
            orderAmountTaxCell.setBorderWidthTop(0);
            orderAmountTaxCell.setBorderWidthRight(0);
            masterFoot.addCell(orderAmountTaxCell);

            PdfPCell orderAmountTaxValue = new PdfPCell(new Phrase(accountInvoice.getOrderAmountTax().toString(), fontEN));
            orderAmountTaxValue.setBorderWidthLeft(0);
            orderAmountTaxValue.setBorderWidthTop(0);
            orderAmountTaxValue.setBorderWidthRight(0);
            masterFoot.addCell(orderAmountTaxValue);

            PdfPCell orderAmountTotalCell = new PdfPCell(new Phrase("价税合计:", fontCN));
            orderAmountTotalCell.setBorderWidthLeft(0);
            orderAmountTotalCell.setBorderWidthTop(0);
            orderAmountTotalCell.setBorderWidthRight(0);
            masterFoot.addCell(orderAmountTotalCell);

            PdfPCell orderAmountTotalValue = new PdfPCell(new Phrase(accountInvoice.getOrderAmountTotal().toString(), fontEN));
//            orderAmountTotalValue.setBorder(0);
            orderAmountTotalValue.setBorderWidthTop(0);
            orderAmountTotalValue.setBorderWidthLeft(0);
            masterFoot.addCell(orderAmountTotalValue);

            //第二行结束
            masterFoot.completeRow();

            doc.add(masterFoot);
            
            
      	
        }else{
    	    
    	    //页脚分割线
    	    LineSeparator line1 = new LineSeparator(1f, 100, BaseColor.BLACK, Element.ALIGN_CENTER, -5f);
    	    doc.add(line1);
        	
        }
        ////////////////////////////////////////////////////////////////////////////////////////////
        
	    
        PdfPTable masterTail = new PdfPTable(8);
        
        masterTail.setTotalWidth(new float[]{45, 65, 45, 105, 45, 65, 45, 105});
        masterTail.setLockedWidth(true);
        masterTail.setSpacingBefore(10);

        PdfPCell cUsernameCell = new PdfPCell(new Phrase("制单:", fontCN));
        cUsernameCell.setBorder(0);
        masterTail.addCell(cUsernameCell);

        PdfPCell cUsernameValue = new PdfPCell(new Phrase(accountInvoice.getcUsername(), fontCN));
        cUsernameValue.setBorder(0);
        masterTail.addCell(cUsernameValue);

        PdfPCell cDatetimeCell = new PdfPCell(new Phrase("制单时间:", fontCN));
        cDatetimeCell.setBorder(0);
        masterTail.addCell(cDatetimeCell);

        PdfPCell cDatetimeValue = new PdfPCell(new Phrase(accountInvoice.getcDatetime().toString(), fontEN));
        cDatetimeValue.setBorder(0);
        masterTail.addCell(cDatetimeValue);

        PdfPCell tUsernameCell = new PdfPCell(new Phrase("审核:", fontCN));
        tUsernameCell.setBorder(0);
        masterTail.addCell(tUsernameCell);

        PdfPCell tUsernameValue = new PdfPCell(new Phrase(accountInvoice.gettUsername(), fontCN));
        tUsernameValue.setBorder(0);
        masterTail.addCell(tUsernameValue);

        PdfPCell tDatetimeCell = new PdfPCell(new Phrase("审核时间:", fontCN));
        tDatetimeCell.setBorder(0);
        masterTail.addCell(tDatetimeCell);

        PdfPCell tDatetimeValue = new PdfPCell(new Phrase(accountInvoice.gettDatetime()==null?"":accountInvoice.gettDatetime().toString(), fontEN));
        tDatetimeValue.setBorder(0);
        masterTail.addCell(tDatetimeValue);


        masterTail.completeRow();
        

        doc.add(masterTail);
	    
        Chunk printTimeChunk = new Chunk("打印时间: ",fontCN);
        String printTime = Utils.getCurrentDateTime().toString();
        Paragraph printTimeParagraph = new Paragraph(printTimeChunk);
        Chunk printTimeValueChunk = new Chunk(printTime,fontEN);
        printTimeParagraph.add(printTimeValueChunk);
        printTimeParagraph.setAlignment(Element.ALIGN_RIGHT);
	    doc.add(printTimeParagraph);
	    
        
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	 

	    
//	    doc.close();
	    
	    
	    
//        int pageNumber = doc.getPageNumber();
//        System.out.println(pageNumber);
//	    Rectangle rect = doc.getPageSize();
//	    System.out.println("rect.getHeight()-->"+rect.getHeight());
//	    System.out.println("rect.getWidth()-->"+rect.getWidth());
//	    System.out.println("rect.getLeft()-->"+rect.getLeft());
//	    System.out.println("rect.getTop()-->"+rect.getTop());
//	    System.out.println("rect.getBottom()-->"+rect.getBottom());
//	    System.out.println("rect.getRight()-->"+rect.getRight());
//	    System.out.println("rect.getBorder()-->"+rect.getBorder());
//	    System.out.println("rect.getBorderWidth()-->"+rect.getBorderWidth());
//	    System.out.println("rect.getBorderWidthTop()-->"+rect.getBorderWidthTop());
//	    System.out.println("rect.getBorderWidthLeft()-->"+rect.getBorderWidthLeft());
//	    System.out.println("rect.getBorderWidthBottom()-->"+rect.getBorderWidthBottom());
//	    System.out.println("rect.getBorderWidthRight()-->"+rect.getBorderWidthRight());

	}
	
	@Override
	public void accountInvoiceQTYFPrintPDF(String fID, Document doc) throws Exception {
		
//	@Test
//	public void saleOrderPrintPDF() throws Exception {
//		log.info("fID-->"+id);
		
//	    Document doc = new Document();// 创建一个PDF文档，我们的PDF内容都写在上面
	    
//	    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File("c://pdftest//saleOrder.pdf"))); // 将pdf文档写入文件

//		String fID = "bf61ec2bc8163a3ad3d8572ad2fee7c6";
		AccountInvoice accountInvoice = accountInvoiceService.getByID(fID);
	   
//	    response.setContentType("application/pdf");
//	    PdfWriter.getInstance(doc, response.getOutputStream());
//	    
//	    doc.open();
	    
	    Font fontEN = new Font(BaseFont.createFont(),9);
	    BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);  	    
//	    Font font = new Font(baseFont, 10, Font.ITALIC);
	    Font fontCN = new Font(baseFont, 9);
	    Paragraph pEnterpriseName = new Paragraph(accountInvoice.getEnterpriseName(),fontCN);
	    // 居中显示
	    pEnterpriseName.setAlignment(Element.ALIGN_CENTER);
	    pEnterpriseName.setSpacingAfter(-10);
	    Paragraph pBillTypeName = new Paragraph(accountInvoice.getBillTypeName(),new Font(baseFont,20));
	    // 居中显示
	    pBillTypeName.setAlignment(Element.ALIGN_CENTER);
	    LineSeparator line = new LineSeparator(1f, 100, BaseColor.BLACK, Element.ALIGN_CENTER, -5f);

	    
	    
	    
	    
	    
	    doc.add(pEnterpriseName);
	    doc.add(pBillTypeName);
	    doc.add(line);
	    
	    
        PdfPTable masterHead = new PdfPTable(8);
        
//        masterHead.setTotalWidth(new float[]{60, 200, 60, 200});
        masterHead.setTotalWidth(new float[]{45, 85, 45, 85, 45, 85, 45, 85});
        masterHead.setLockedWidth(true);
        masterHead.setSpacingBefore(10);
        
        PdfPCell ordrDateCell = new PdfPCell(new Phrase("单据日期:", fontCN));
        ordrDateCell.setUseBorderPadding(true);
        //
        // Setting cell's border width and color
        //
        ordrDateCell.setBorderWidth(0f);
//        ordrDateCell.setBorderColor(BaseColor.BLUE);
        masterHead.addCell(ordrDateCell);

        PdfPCell ordrDateValue = new PdfPCell(new Phrase(accountInvoice.getOrderDate().toString(), fontEN));
        ordrDateValue.setUseBorderPadding(true);
        ordrDateValue.setBorderWidth(0f);
        //
        // Setting cell's background color
        //
//        cell2.setBackgroundColor(BaseColor.GRAY);
        //
        // Setting cell's individual border color
        //
//        cell2.setBorderWidthTop(1f);
//        cell2.setBorderColorTop(BaseColor.RED);
//        cell2.setBorderColorRight(BaseColor.GREEN);
//        cell2.setBorderColorBottom(BaseColor.BLUE);
//        cell2.setBorderColorLeft(BaseColor.BLACK);
        masterHead.addCell(ordrDateValue);

        PdfPCell auditCell = new PdfPCell(new Phrase("单据状态:", fontCN));
        auditCell.setUseBorderPadding(true);
        auditCell.setBorderWidth(0f);
        //
        // Setting cell's individual border width
        //
//        cell3.setBorderWidthTop(2f);
//        cell3.setBorderWidthRight(1f);
//        cell3.setBorderWidthBottom(2f);
//        cell3.setBorderWidthLeft(1f);
        masterHead.addCell(auditCell);

        String auditStatus = "待审核";
        String audit = accountInvoice.getAudit();
        String state = accountInvoice.getState();
        if(audit.equals("confirm")){
        	auditStatus = "已审核";
        }else if(audit.equals("active") && state.equals("confirm")){
        	auditStatus = "审核中";
        }else{
        	auditStatus = "待审核";
        }
        
       PdfPCell auditValue = new PdfPCell(new Phrase(auditStatus, fontCN));
       auditValue.setUseBorderPadding(true);
       auditValue.setBorderWidth(0f);
        //
        // Setting cell's individual border width
        //
//        cell4.setBorderWidthTop(2f);
//        cell4.setBorderWidthRight(1f);
//        cell4.setBorderWidthBottom(2f);
//        cell4.setBorderWidthLeft(1f);
        masterHead.addCell(auditValue);
        
        PdfPCell customerNoCell = new PdfPCell(new Phrase("对象编码:", fontCN));
        customerNoCell.setBorder(0);
        masterHead.addCell(customerNoCell);
        PdfPCell customerNoValue = new PdfPCell(new Phrase(accountInvoice.getCustomerNo(), fontEN));
        customerNoValue.setBorder(0);
        masterHead.addCell(customerNoValue);
        
        PdfPCell shortNameCell = new PdfPCell(new Phrase("对象简称:", fontCN));
        shortNameCell.setBorder(0);
        masterHead.addCell(shortNameCell);
        PdfPCell shortNameValue = new PdfPCell(new Phrase(accountInvoice.getShortName(), fontCN));
        shortNameValue.setBorder(0);
        masterHead.addCell(shortNameValue);

        //第一行结束
        masterHead.completeRow();
        
        PdfPCell orderNoCell = new PdfPCell(new PdfPCell(new Phrase("单号:", fontCN)));
        orderNoCell.setBorder(0);
        masterHead.addCell(orderNoCell);
        PdfPCell orderNoValue = new PdfPCell(new PdfPCell(new Phrase(accountInvoice.getAccountInvoiceNo(), fontEN)));
        orderNoValue.setBorder(0);
        masterHead.addCell(orderNoValue);
        
        PdfPCell discountRateMCell = new PdfPCell(new PdfPCell(new Phrase("折扣率:", fontCN)));
        discountRateMCell.setBorder(0);
        masterHead.addCell(discountRateMCell);
        String discountRate = accountInvoice.getDiscountRate().multiply(new BigDecimal(100)).toString() + "%";
        PdfPCell discountRateMValue = new PdfPCell(new PdfPCell(new Phrase(discountRate, fontEN)));
        discountRateMValue.setBorder(0);
        masterHead.addCell(discountRateMValue);
        
        PdfPCell customerNameCell = new PdfPCell(new Phrase("交易对象:", fontCN));
        customerNameCell.setBorder(0);
        masterHead.addCell(customerNameCell);
        PdfPCell customerNameValue = new PdfPCell(new Phrase(accountInvoice.getCustomerName(), fontCN));
        customerNameValue.setBorder(0);
        customerNameValue.setColspan(3);
        masterHead.addCell(customerNameValue);
        //第二行结束
        masterHead.completeRow();
        
        PdfPCell factoryNoCell = new PdfPCell(new PdfPCell(new Phrase("门店编码:", fontCN)));
        factoryNoCell.setBorder(0);
        masterHead.addCell(factoryNoCell);
        PdfPCell factoryNoValue = new PdfPCell(new PdfPCell(new Phrase("", fontEN)));
        factoryNoValue.setBorder(0);
        masterHead.addCell(factoryNoValue);
        
        PdfPCell factoryNameCell = new PdfPCell(new PdfPCell(new Phrase("门店名称:", fontCN)));
        factoryNameCell.setBorder(0);
        masterHead.addCell(factoryNameCell);
        PdfPCell factoryNameValue = new PdfPCell(new PdfPCell(new Phrase("", fontCN)));
        factoryNameValue.setBorder(0);
        masterHead.addCell(factoryNameValue);
        
        PdfPCell employeeNameCell = new PdfPCell(new Phrase("经办人:", fontCN));
        employeeNameCell.setBorder(0);
        masterHead.addCell(employeeNameCell);
        PdfPCell employeeNameValue = new PdfPCell(new Phrase(accountInvoice.getEmployeeName(), fontCN));
        employeeNameValue.setBorder(0);
        employeeNameValue.setColspan(3);
        masterHead.addCell(employeeNameValue);

        //第五行结束
        masterHead.completeRow();
        
        PdfPCell paymentTermLabelCell = new PdfPCell(new Phrase("付款条件:", fontCN));
        paymentTermLabelCell.setBorder(0);
        masterHead.addCell(paymentTermLabelCell);
        PdfPCell paymentTermLabelValue = new PdfPCell(new Phrase(accountInvoice.getPaymentTermLabel(), fontCN));
        paymentTermLabelValue.setBorder(0);
        paymentTermLabelValue.setColspan(7);
        masterHead.addCell(paymentTermLabelValue);
        //第七行结束
        masterHead.completeRow();
        
        PdfPCell commentsCell = new PdfPCell(new Phrase("备注:", fontCN));
        commentsCell.setBorder(0);
        masterHead.addCell(commentsCell);
        PdfPCell commentsValue = new PdfPCell(new Phrase(accountInvoice.getComments(), fontCN));
        commentsValue.setBorder(0);
        commentsValue.setColspan(7);
        masterHead.addCell(commentsValue);
        
        //第n行结束
        masterHead.completeRow();

        doc.add(masterHead);
//	    doc.add(line);
	    

        /*
        Image image = Image.getInstance("c://pdftest//smp.png");

        image.setAlignment(Image.ALIGN_RIGHT);
        // 设置边框
        image.setBorder(Image.BOX);
        image.setBorderWidth(2);
        image.setBorderColor(BaseColor.RED);
        // 设置图片大小
        
//        ScaleToFit有两个参数，指的是长和宽的最大值，但是图片的长宽比还是不会变的
//        ScaleAbsoluteHeight设置图片的高度，不管长宽比 ScaleAbsoluteWidth设置图片的宽度，不管长宽比
//        ScalePercent等比例缩放
        
//         image.scaleToFit(100, 100);
//         image.scaleAbsoluteHeight(100f);
//         image.scaleAbsoluteWidth(100f);

        image.scalePercent(50f);
        // 图片旋转30度
        image.setRotationDegrees(30);

        doc.add(image);
        */
        
        
        
        
        
	    //////////////////////////////////////////////////////////////////////////////////////////
	    
        PdfPTable details = new PdfPTable(8);
        details.setTotalWidth(new float[]{15, 70, 70, 80, 65, 75, 65, 80});//520
        details.setLockedWidth(true);
        details.setSpacingBefore(10);

        PdfPCell sharpCell = new PdfPCell(new Phrase("序号", fontCN));
//        sharpCell.setBorder(0);
        sharpCell.setRowspan(2);
        sharpCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        sharpCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        details.addCell(sharpCell);

        PdfPCell itemNoCell = new PdfPCell(new Phrase("项目", fontCN));
//        itemNoCell.setBorder(0);
//        itemNoCell.setBorderWidthTop(0);
        itemNoCell.setBorderWidthLeft(0);
        itemNoCell.setBorderWidthBottom(0);
        itemNoCell.setBorderWidthRight(0);
        itemNoCell.setColspan(2);
        details.addCell(itemNoCell);

        PdfPCell projectNoCell = new PdfPCell(new Phrase("类型", fontCN));
//        projectNoCell.setBorder(0);
        projectNoCell.setBorderWidthLeft(0);
        projectNoCell.setBorderWidthBottom(0);
        projectNoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(projectNoCell);

        PdfPCell requirementDateCell = new PdfPCell(new Phrase("金额", fontCN));
//        requirementDateCell.setBorder(0);
        requirementDateCell.setBorderWidthLeft(0);
        requirementDateCell.setBorderWidthBottom(0);
        requirementDateCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(requirementDateCell);

        PdfPCell itemAmountsCell = new PdfPCell(new Phrase("", fontCN));
//        itemAmountsCell.setBorder(0);
        itemAmountsCell.setBorderWidthLeft(0);
        itemAmountsCell.setBorderWidthBottom(0);
        itemAmountsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(itemAmountsCell);

        PdfPCell taxRatesCell = new PdfPCell(new Phrase("项目号", fontCN));
//        taxRatesCell.setBorder(0);
        taxRatesCell.setBorderWidthLeft(0);
        taxRatesCell.setBorderWidthBottom(0);
        taxRatesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(taxRatesCell);

        PdfPCell commentssCell = new PdfPCell(new Phrase("备注", fontCN));
//        commentssCell.setBorder(0);
        commentssCell.setBorderWidthLeft(0);
        commentssCell.setRowspan(2);
        details.addCell(commentssCell);
        
        details.completeRow();
        //第一行结束


        PdfPCell floorNoCell = new PdfPCell(new Phrase("对方科目名称", fontCN));
//        floorNoCell.setBorder(0);
        floorNoCell.setBorderWidthTop(0);
        floorNoCell.setBorderWidthLeft(0);
        floorNoCell.setBorderWidthRight(0);
        floorNoCell.setColspan(2);
        details.addCell(floorNoCell);

        PdfPCell storageNoCell = new PdfPCell(new Phrase("对方科目", fontCN));
//        storageNoCell.setBorder(0);
        storageNoCell.setBorderWidthTop(0);
        storageNoCell.setBorderWidthLeft(0);
        storageNoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(storageNoCell);

        PdfPCell emptyCell = new PdfPCell(new Phrase("", fontCN));
//        emptyCell.setBorder(0);
        emptyCell.setBorderWidthTop(0);
        emptyCell.setBorderWidthLeft(0);
        emptyCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(emptyCell);

        PdfPCell orderAmountCell = new PdfPCell(new Phrase("", fontCN));
//        orderAmountCell.setBorder(0);
        orderAmountCell.setBorderWidthTop(0);
        orderAmountCell.setBorderWidthLeft(0);
        orderAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountCell);

        PdfPCell orderAmountTotalsCell = new PdfPCell(new Phrase("", fontCN));
//        orderAmountTotalsCell.setBorder(0);
        orderAmountTotalsCell.setBorderWidthTop(0);
        orderAmountTotalsCell.setBorderWidthLeft(0);
        orderAmountTotalsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountTotalsCell);

        details.completeRow();
        //第四行结束
        
        
//        doc.add(details);
        
        ////////////////////////////////////////////////////////////////////////////////////////////
        
        
	    //////////////////////////////////////////////////////////////////////////////////////////
        List<AccountInvoiceDetail> accountInvoiceDetails = accountInvoiceDetailService.getByMasterID(fID);
        if(accountInvoiceDetails.size()>0){
    	    
//            PdfPTable detailsValue = new PdfPTable(8);
//            
//            detailsValue.setTotalWidth(new float[]{20, 70, 70, 80, 80, 80, 60, 60});//520
//            detailsValue.setLockedWidth(true);
//            detailsValue.setSpacingBefore(10);
            
            for(int i=0;i<accountInvoiceDetails.size();i++){
            	AccountInvoiceDetail accountInvoiceDetail = accountInvoiceDetails.get(i);

            	//序号
            	String rowNo = String.valueOf(i+1);
                PdfPCell sharpValue = new PdfPCell(new Phrase(rowNo, fontEN));
//                sharpValue.setBorder(0);
                sharpValue.setBorderWidthTop(0);
                sharpValue.setRowspan(2);
                sharpValue.setHorizontalAlignment(Element.ALIGN_CENTER);
                sharpValue.setVerticalAlignment(Element.ALIGN_MIDDLE);
                details.addCell(sharpValue);

                PdfPCell itemNoValue = new PdfPCell(new Phrase(accountInvoiceDetail.getItemName(), fontCN));
//                itemNoValue.setBorder(0);
                itemNoValue.setBorderWidthTop(0);
                itemNoValue.setBorderWidthLeft(0);
                itemNoValue.setBorderWidthBottom(0);
                itemNoValue.setBorderWidthRight(0);
                itemNoValue.setColspan(2);
                details.addCell(itemNoValue);

                PdfPCell projectNoValue = new PdfPCell(new Phrase(accountInvoiceDetail.getItemNo(), fontCN));
//                projectNoValue.setBorder(0);
                projectNoValue.setBorderWidthTop(0);
                projectNoValue.setBorderWidthLeft(0);
                projectNoValue.setBorderWidthBottom(0);
                projectNoValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(projectNoValue);

                PdfPCell requirementDateValue = new PdfPCell(new Phrase(accountInvoiceDetail.getOrderAmountTotal().toString(), fontEN));
//                requirementDateValue.setBorder(0);
                requirementDateValue.setBorderWidthTop(0);
                requirementDateValue.setBorderWidthLeft(0);
                requirementDateValue.setBorderWidthBottom(0);
                requirementDateValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(requirementDateValue);

                PdfPCell itemAmountValue = new PdfPCell(new Phrase("", fontEN));
//                itemAmountValue.setBorder(0);
                itemAmountValue.setBorderWidthTop(0);
                itemAmountValue.setBorderWidthLeft(0);
                itemAmountValue.setBorderWidthBottom(0);
                itemAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(itemAmountValue);

                PdfPCell taxRatesValue = new PdfPCell(new Phrase(accountInvoiceDetail.getProjectNo(), fontCN));
//                taxRatesValue.setBorder(0);
                taxRatesValue.setBorderWidthTop(0);
                taxRatesValue.setBorderWidthLeft(0);
                taxRatesValue.setBorderWidthBottom(0);
                taxRatesValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(taxRatesValue);

                PdfPCell commentssValue = new PdfPCell(new Phrase(accountInvoiceDetail.getComments(), fontCN));
//                commentssValue.setBorder(0);
                commentssValue.setBorderWidthTop(0);
                commentssValue.setBorderWidthLeft(0);
                commentssValue.setRowspan(2);
                details.addCell(commentssValue);
                
                details.completeRow();
                //第一行结束
              

              PdfPCell floorNoValue = new PdfPCell(new Phrase(accountInvoiceDetail.getCaptionFullName(), fontCN));
//              floorNoValue.setBorder(0);
              floorNoValue.setBorderWidthTop(0);
              floorNoValue.setBorderWidthLeft(0);
              floorNoValue.setBorderWidthRight(0);
              floorNoValue.setColspan(2);
              details.addCell(floorNoValue);

              PdfPCell storageNoValue = new PdfPCell(new Phrase(accountInvoiceDetail.getCaptionNo(), fontCN));
//              storageNoValue.setBorder(0);
              storageNoValue.setBorderWidthTop(0);
              storageNoValue.setBorderWidthLeft(0);
              storageNoValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(storageNoValue);

              PdfPCell emptyValue = new PdfPCell(new Phrase("", fontCN));
//              emptyValue.setBorder(0);
              emptyValue.setBorderWidthTop(0);
              emptyValue.setBorderWidthLeft(0);
              emptyValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(emptyValue);

              PdfPCell orderAmountValue = new PdfPCell(new Phrase("", fontEN));
//              orderAmountValue.setBorder(0);
              orderAmountValue.setBorderWidthTop(0);
              orderAmountValue.setBorderWidthLeft(0);
              orderAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountValue);

              PdfPCell orderAmountTotalValue = new PdfPCell(new Phrase("", fontEN));
//              orderAmountTotalValue.setBorder(0);
              orderAmountTotalValue.setBorderWidthTop(0);
              orderAmountTotalValue.setBorderWidthLeft(0);
              orderAmountTotalValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountTotalValue);

              details.completeRow();
              //第四行结束
              
            }
            
            doc.add(details);
            //子表结束
            
            
            
//    	    doc.add(line);

    	    
            PdfPTable masterFoot = new PdfPTable(8);
            
            masterFoot.setTotalWidth(new float[]{45, 85, 45, 85, 45, 85, 45, 85});
            masterFoot.setLockedWidth(true);
//            masterFoot.setSpacingBefore(10);

            PdfPCell detailsCountCell = new PdfPCell(new Phrase("金额:", fontCN));
//            detailsCountCell.setBorder(0);
            detailsCountCell.setBorderWidthTop(0);
//            detailsCountCell.setBorderWidthBottom(0);
            detailsCountCell.setBorderWidthRight(0);
            masterFoot.addCell(detailsCountCell);

            PdfPCell detailsCountValue = new PdfPCell(new Phrase(String.valueOf(accountInvoice.getOrderAmountTotal()), fontEN));
            detailsCountValue.setBorderWidthTop(0);
//          detailsCountValue.setBorderWidthBottom(0);
            detailsCountValue.setBorderWidthLeft(0);
            detailsCountValue.setBorderWidthRight(0);
            masterFoot.addCell(detailsCountValue);

            PdfPCell r1emptyCell = new PdfPCell(new Phrase(""));
//            r1emptyCell.setBorder(0);
            r1emptyCell.setBorderWidthTop(0);
//            r1emptyCell.setBorderWidthBottom(0);
            r1emptyCell.setBorderWidthLeft(0);
            r1emptyCell.setColspan(6);
            masterFoot.addCell(r1emptyCell);

            //第一行结束
            masterFoot.completeRow();

            doc.add(masterFoot);
            
            
      	
        }else{
    	    
    	    //页脚分割线
    	    LineSeparator line1 = new LineSeparator(1f, 100, BaseColor.BLACK, Element.ALIGN_CENTER, -5f);
    	    doc.add(line1);
        	
        }
        ////////////////////////////////////////////////////////////////////////////////////////////
        
	    
        PdfPTable masterTail = new PdfPTable(8);
        
        masterTail.setTotalWidth(new float[]{45, 65, 45, 105, 45, 65, 45, 105});
        masterTail.setLockedWidth(true);
        masterTail.setSpacingBefore(10);

        PdfPCell cUsernameCell = new PdfPCell(new Phrase("制单:", fontCN));
        cUsernameCell.setBorder(0);
        masterTail.addCell(cUsernameCell);

        PdfPCell cUsernameValue = new PdfPCell(new Phrase(accountInvoice.getcUsername(), fontCN));
        cUsernameValue.setBorder(0);
        masterTail.addCell(cUsernameValue);

        PdfPCell cDatetimeCell = new PdfPCell(new Phrase("制单时间:", fontCN));
        cDatetimeCell.setBorder(0);
        masterTail.addCell(cDatetimeCell);

        PdfPCell cDatetimeValue = new PdfPCell(new Phrase(accountInvoice.getcDatetime().toString(), fontEN));
        cDatetimeValue.setBorder(0);
        masterTail.addCell(cDatetimeValue);

        PdfPCell tUsernameCell = new PdfPCell(new Phrase("审核:", fontCN));
        tUsernameCell.setBorder(0);
        masterTail.addCell(tUsernameCell);

        PdfPCell tUsernameValue = new PdfPCell(new Phrase(accountInvoice.gettUsername(), fontCN));
        tUsernameValue.setBorder(0);
        masterTail.addCell(tUsernameValue);

        PdfPCell tDatetimeCell = new PdfPCell(new Phrase("审核时间:", fontCN));
        tDatetimeCell.setBorder(0);
        masterTail.addCell(tDatetimeCell);

        PdfPCell tDatetimeValue = new PdfPCell(new Phrase(accountInvoice.gettDatetime()==null?"":accountInvoice.gettDatetime().toString(), fontEN));
        tDatetimeValue.setBorder(0);
        masterTail.addCell(tDatetimeValue);


        masterTail.completeRow();
        

        doc.add(masterTail);
	    
        Chunk printTimeChunk = new Chunk("打印时间: ",fontCN);
        String printTime = Utils.getCurrentDateTime().toString();
        Paragraph printTimeParagraph = new Paragraph(printTimeChunk);
        Chunk printTimeValueChunk = new Chunk(printTime,fontEN);
        printTimeParagraph.add(printTimeValueChunk);
        printTimeParagraph.setAlignment(Element.ALIGN_RIGHT);
	    doc.add(printTimeParagraph);
	    
        
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	 

	    
//	    doc.close();
	    
	    
	    
//        int pageNumber = doc.getPageNumber();
//        System.out.println(pageNumber);
//	    Rectangle rect = doc.getPageSize();
//	    System.out.println("rect.getHeight()-->"+rect.getHeight());
//	    System.out.println("rect.getWidth()-->"+rect.getWidth());
//	    System.out.println("rect.getLeft()-->"+rect.getLeft());
//	    System.out.println("rect.getTop()-->"+rect.getTop());
//	    System.out.println("rect.getBottom()-->"+rect.getBottom());
//	    System.out.println("rect.getRight()-->"+rect.getRight());
//	    System.out.println("rect.getBorder()-->"+rect.getBorder());
//	    System.out.println("rect.getBorderWidth()-->"+rect.getBorderWidth());
//	    System.out.println("rect.getBorderWidthTop()-->"+rect.getBorderWidthTop());
//	    System.out.println("rect.getBorderWidthLeft()-->"+rect.getBorderWidthLeft());
//	    System.out.println("rect.getBorderWidthBottom()-->"+rect.getBorderWidthBottom());
//	    System.out.println("rect.getBorderWidthRight()-->"+rect.getBorderWidthRight());

	}

	/*
	//生成销售发票
	@Transactional
	@Override
	public AccountInvoice accountInvoiceXSFPInsert(JSONObject params){
		log.info("这是前台输入的参数（JSON格式字符串）-->"+params);
		String rowID = params.getString("rowID");
		String flowType = params.getString("flowType");
		String autoState = params.getString("autoState");
		String autoPayment = params.getString("autoPayment");
		System.out.println("flowType-->"+flowType);
		System.out.println("autoState-->"+autoState);
		
		[
            {value:0,label:'0:不送审自动审核'}
            ,{value:1,label:'1:非工作流审签'}
            ,{value:2,label:'2:自由工作流审签'}
            ,{value:3,label:'3:工作流审签'}
        ];
		

//		String billTypeName = params.getString("billTypeName");
//		String invoiceCode = params.getString("invoiceCode");
//		String invoiceDate = params.getString("invoiceDate");
//		String orderDate = params.getString("orderDate");
//		String comments = params.getString("comments");
//		String enterpriseID = obj.getString("enterpriseID");
		log.info("autoPayment-->"+autoPayment);
//		log.info("billType-->"+billType);
//		log.info("billTypeName-->"+billTypeName);
//		log.info("orderDate-->"+orderDate);
//		log.info("comments-->"+comments);
		
//		String cUsercode = SecurityService.getCurrentPerson().getsCode();
//		String cUsername = SecurityService.getCurrentPerson().getsName();
//		String userId = SecurityService.getCurrentPerson().getsID();
		
		String cUsercode = params.getString("personCode");
		String cUsername = params.getString("personName");
		String userId = params.getString("personID");
		
		String employeeNo = params.getString("employeeNo");
		String employeeName = params.getString("employeeName");

//		String enterpriseNo = SecurityService.getCurrentOgn().getsFID();
//		String enterpriseName = SecurityService.getCurrentOgn().getsName();
		
		StorageRecord storageRecord = storageRecordService.getByID(rowID);

		AccountInvoice accountInvoice = null;
		//打包主表
		if(storageRecord!=null){
			
//			String billType = "XSFP";//销售发票
			accountInvoice = this.accountInvoiceXSFPInsert(storageRecord, cUsercode, cUsername, userId, autoState, flowType, autoPayment, employeeNo, employeeName);
		}
		
		if(autoState!=null && "Y".equals(autoState)){
			//提交工单
			this.accountInvoiceConfirm(accountInvoice.getfID(),cUsercode,cUsername,userId);
		}
		
		放在了confirmAccountInvoice中进行
		if(accountInvoice.getFlowType()==0){
			//审核
			this.agreeItAccountInvoice(accountInvoice.getfID());
		}
		

		return accountInvoice;
	}
	*/
		
	/*
	//生成销售发票（合并收款）
	@Transactional
	@Override
	public AccountInvoice accountInvoiceXSFPBuild(JSONObject params){
//		log.info("这是前台输入的参数（JSON格式字符串）-->"+params);
		@SuppressWarnings("unchecked")
		List<String> ids =  (List<String>) params.get("ids");

//			String projectNo = params.getString("projectNo");
//			String customerID = params.getString("customerID");

//		String billID = params.getString("billID");
//		String billType = params.getString("billType");
//		String billTypeName = params.getString("billTypeName");
//		String invoiceCode = params.getString("invoiceCode");
//		String invoiceDate = params.getString("invoiceDate");
//		String orderDate = params.getString("orderDate");
//		String comments = params.getString("comments");
		
//		String enterpriseID = obj.getString("enterpriseID");
//		log.info("billID-->"+billID);
//		log.info("billType-->"+billType);
//		log.info("billTypeName-->"+billTypeName);
//		log.info("orderDate-->"+orderDate);
//		log.info("comments-->"+comments);
		
		String cUsercode = null;//SecurityService.getCurrentPerson().getsCode();
		String cUsername = null;//SecurityService.getCurrentPerson().getsName();
		String userId = null;//SecurityService.getCurrentPerson().getsID();
		String enterpriseNo = null;//SecurityService.getCurrentOgn().getsFID();
		String enterpriseName = null;//SecurityService.getCurrentOgn().getsName();
		String employeeNo = null;//SecurityService.getCurrentPsm().getsFID();
		String employeeName = null;//SecurityService.getCurrentPsm().getsFName();
		
		String projectNo = null;
		String customerID = null;
		
		if(ids.size()>0){
			StorageRecordDetail storageRecordDetail = storageRecordDetailService.getByID(ids.get(0));
			customerID = storageRecordDetail.getProviderID();
			projectNo = storageRecordDetail.getProjectNo();
			
		}
		
		FileCustomer fileCustomer = null;
		if(customerID!=null && !"".equals(customerID)){
			fileCustomer = fileCustomerService.getByID(customerID);
		}
		
		String dealObject = null;
		String dealObjectLabel = null;
		String customerNo = null;
		String shortName = null;
		String customerName = null;
		
		String invoiceCategory = null;
		String invoiceCategoryLabel = null;
		
		int taxType = 1;
		String taxTypeLabel = "1.应税内含";
		BigDecimal taxRate = BigDecimal.ZERO;
		
		
		if(fileCustomer!=null){
			dealObject = fileCustomer.getStorageTypeD();
			dealObjectLabel = fileCustomer.getStorageTypeDLabel();
			customerNo = fileCustomer.getCustomerNo();
			shortName = fileCustomer.getShortName();
			customerName = fileCustomer.getCustomerName();
			
			invoiceCategory = fileCustomer.getInvoiceCategory();
			invoiceCategoryLabel = fileCustomer.getInvoiceCategoryLabel();

			taxType = fileCustomer.getTaxType();
			taxTypeLabel = fileCustomer.getTaxTypeLabel();
			taxRate = fileCustomer.getTaxRate();

		}

		AccountInvoice accountInvoice = null;
		List<AccountInvoiceDetail> accountInvoiceDetails = null;
		//打包主表
		if(ids.size()>0){
			
//			String billType = "XSFP";//销售发票
			accountInvoice = accountInvoiceService.packing("XSFP", cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
			
			//开票日期
			if(orderDate!=null && !orderDate.equals("")){
				accountInvoice.setOrderDate(Date.valueOf(orderDate));
			}
			
			//发票日期
			if(orderDate!=null && !orderDate.equals("")){
				accountInvoice.setInvoiceDate(Date.valueOf(invoiceDate));
			}
			
			accountInvoice.setInvoiceCode(invoiceCode);
			
			accountInvoice.setComments("合并结算");
			
//			StorageRecord storageRecord = storageRecordService.getByID(billID);
			accountInvoice.setProjectNo(projectNo);
			
			accountInvoice.setOrigin("HBJS");
			accountInvoice.setOriginName("合并结算");
			accountInvoice.setOriginNo(projectNo);
			
			accountInvoice.setEmployeeNo(employeeNo);
			accountInvoice.setEmployeeName(employeeName);

			accountInvoice.setDealObject(dealObject);
			accountInvoice.setDealObjectLabel(dealObjectLabel);
			accountInvoice.setCustomerID(customerID);
			accountInvoice.setCustomerNo(customerNo);
			accountInvoice.setShortName(shortName);
			accountInvoice.setCustomerName(customerName);
			
			accountInvoice.setTaxType(taxType);
			accountInvoice.setTaxTypeLabel(taxTypeLabel);
			accountInvoice.setTaxRate(taxRate);
			
			accountInvoice.setInvoiceCategory(invoiceCategory);
			accountInvoice.setInvoiceCategoryLabel(invoiceCategoryLabel);
			
//			accountInvoice.setAccountBank(storageRecord.getb);
//			accountInvoice.setAccountNo(storageRecord.getacc);
//			accountInvoice.setTaxNo(storageRecord.gettax);
			
			accountInvoice.setOrderNo(null);
		
			accountInvoice.setDirection(1);
			
			int direction = accountInvoice.getDirection();
			BigDecimal bgDirection = new BigDecimal(direction);
			
			
			//子表
			
			List<StorageRecordDetail> storageRecordDetails = storageRecordDetailService.getByMasterID(billID);
			if(storageRecordDetails.size()>0){
				accountInvoiceDetails = new ArrayList<AccountInvoiceDetail>();
			}
			for(StorageRecordDetail storageRecordDetail : storageRecordDetails){
			
			
			if(ids.size()>0){
				accountInvoiceDetails = new ArrayList<AccountInvoiceDetail>();
			}
			
			for(int i=0;i<ids.size();i++){
				System.out.println(ids.get(i));
				
				StorageRecordDetail storageRecordDetail = storageRecordDetailService.getByID(ids.get(i));
				
				AccountInvoiceDetail accountInvoiceDetail = accountInvoiceService.packing(accountInvoice);
				accountInvoice.setMaxDetailNo(accountInvoice.getMaxDetailNo()+1);
				accountInvoice.setDetailsCount(accountInvoice.getDetailsCount()+1);
				
				accountInvoiceDetail.setOrigin(storageRecordDetail.getBillType());
				accountInvoiceDetail.setOriginName(storageRecordDetail.getBillTypeName());
				accountInvoiceDetail.setOriginNo(storageRecordDetail.getRecordDetailNo());
				
				//物料
				accountInvoiceDetail.setItemID(storageRecordDetail.getItemID());
				accountInvoiceDetail.setItemNo(storageRecordDetail.getItemNo());
				accountInvoiceDetail.setItemDescribe(storageRecordDetail.getItemDescribe());
				accountInvoiceDetail.setItemProperty(storageRecordDetail.getItemProperty());
				accountInvoiceDetail.setUnitCode(storageRecordDetail.getUnitCode());
				accountInvoiceDetail.setUnitName(storageRecordDetail.getUnitName());
				
//				accountInvoiceDetail.setFactoryNo(storageRecordDetail.getFactoryNo());
//				accountInvoiceDetail.setFactoryName(storageRecordDetail.getFactoryName());
				
//				accountInvoiceDetail.setStorageType(storageRecordDetail.getStorageType());
//				accountInvoiceDetail.setStorageTypeLabel(storageRecordDetail.getStorageTypeLabel());
//				accountInvoiceDetail.setStorageID(storageRecordDetail.getStorageID());
//				accountInvoiceDetail.setStorageNo(storageRecordDetail.getStorageNo());
//				accountInvoiceDetail.setStorageName(storageRecordDetail.getStorageName());
//				accountInvoiceDetail.setFloorNo(storageRecordDetail.getFloorNo());

				//单价
				accountInvoiceDetail.setTaxType(storageRecordDetail.getTaxType());
				accountInvoiceDetail.setTaxTypeLabel(storageRecordDetail.getTaxTypeLabel());
				accountInvoiceDetail.setTaxRate(storageRecordDetail.getTaxRate());
//				System.out.println(storageRecordDetail.getTaxRate());
				accountInvoiceDetail.setItemPrice(storageRecordDetail.getItemPrice());
				accountInvoiceDetail.setDiscountRate(storageRecordDetail.getDiscountRate());
				//数量
				accountInvoiceDetail.setItemAmount(storageRecordDetail.getPriceAmount().subtract(storageRecordDetail.getInvoiceQuantityIng().add(storageRecordDetail.getInvoiceQuantity())));
				
				//计算金额
				JSONObject json = AppSystemService.taxCalculate(accountInvoiceDetail.getItemAmount(), accountInvoiceDetail.getItemPrice(), accountInvoiceDetail.getTaxType(), accountInvoiceDetail.getTaxRate(), accountInvoiceDetail.getDiscountRate());
				
				accountInvoiceDetail.setOrderAmount(json.getBigDecimal("orderAmount"));
				accountInvoiceDetail.setOrderAmountOld(json.getBigDecimal("orderAmountOld"));
				accountInvoiceDetail.setOrderAmountTax(json.getBigDecimal("orderAmountTax"));
				accountInvoiceDetail.setOrderAmountTotal(json.getBigDecimal("orderAmountTotal"));
				
				accountInvoiceDetail.setDealPrice(accountInvoiceDetail.getItemPrice());
				accountInvoiceDetail.setBillDate(storageRecordDetail.getOrderDate());
				accountInvoiceDetail.setOrderNo(storageRecordDetail.getOrderNo());
				accountInvoiceDetail.setProjectNo(storageRecordDetail.getProjectNo());
				
				//获取会计科目（结算账户）的全路径信息
//				AccountCaption accountCaption = accountCaptionService.getByID(captionID);
//				String captionFullNo = accountCaption.getCaptionFullNo();
//				String captionFullName = accountCaption.getCaptionFullName();
				
				//累计主表合计金额
				accountInvoice.setItemAmount(accountInvoice.getItemAmount().add(accountInvoiceDetail.getItemAmount()));
				accountInvoice.setOrderAmount(accountInvoice.getOrderAmount().add(accountInvoiceDetail.getOrderAmount()));
				accountInvoice.setOrderAmountOld(accountInvoice.getOrderAmountOld().add(accountInvoiceDetail.getOrderAmountOld()));
				accountInvoice.setOrderAmountTax(accountInvoice.getOrderAmountTax().add(accountInvoiceDetail.getOrderAmountTax()));
				accountInvoice.setOrderAmountTotal(accountInvoice.getOrderAmountTotal().add(accountInvoiceDetail.getOrderAmountTotal()));
				
				//账金额，保留两位小数
				BigDecimal accountAmountOld = accountInvoiceDetail.getOrderAmountOld().multiply(bgDirection);
				accountAmountOld.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
				BigDecimal accountAmountTax = accountInvoiceDetail.getOrderAmountTax().multiply(bgDirection);
				accountAmountTax.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
				BigDecimal accountAmountTotal = accountInvoiceDetail.getOrderAmountTotal().multiply(bgDirection);
				accountAmountTotal.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
				accountInvoice.setAccountAmountOld(accountAmountOld);
				accountInvoice.setAccountAmountTax(accountAmountTax);
				accountInvoice.setAccountAmountTotal(accountAmountTotal);
				
				
				accountInvoiceDetails.add(accountInvoiceDetail);
			}
		
		}
		//写入数据库主表
		if(accountInvoice!=null){
			accountInvoiceService.insert(accountInvoice);
		}
		//插入子表
		if(accountInvoiceDetails!=null){
			for(AccountInvoiceDetail accountInvoiceDetail :accountInvoiceDetails){
				accountInvoiceDetailService.insert(accountInvoiceDetail);
			}
		}
		
		return accountInvoice;
	}
	*/
	
	
	//生成销售发票和采购发票
	@Transactional
	@Override
	public AccountInvoice accountInvoiceInsert(
			StorageRecord storageRecord
//			,String billType
//			,String billTypeName 
//			,String systemCode 
//			,int flowType 
//			,String revOpay 
//			,int direction 
//			,String autoCode 
//			,String origin 
//			,String originName 
//			,String billNo 
			,int flowType ,int cashSettle/*现结*/
			,String cUsercode,String cUsername,String userId
			,String employeeNo,String employeeName){

		
		/*
		[
            {value:0,label:'0:不送审自动审核'}
            ,{value:1,label:'1:非工作流审签'}
            ,{value:2,label:'2:自由工作流审签'}
            ,{value:3,label:'3:工作流审签'}
        ];
		*/

//		System.out.println("autoPayment-->"+autoPayment);
		
		String billType = null;
		if("XSCK".equals(storageRecord.getBillType()) || "XSRK".equals(storageRecord.getBillType())){
			billType = "XSFP";//销售发票
		}
		if("CGRK".equals(storageRecord.getBillType()) || "CGCK".equals(storageRecord.getBillType())){
			billType = "CGFP";//采购发票
		}
		if("WWRK".equals(storageRecord.getBillType()) || "WWCK".equals(storageRecord.getBillType())){
			billType = "CGFP";//采购发票
		}
		String enterpriseNo = storageRecord.getEnterpriseNo();
		String enterpriseName = storageRecord.getEnterpriseName();
		
		Map<String,Object> map = settingService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
		String systemCode = (String) map.get("systemCode");
//		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
//		String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
		String origin = (String) map.get("origin");
		String originName = (String) map.get("originName");
		String billNo = (String) map.get("billNo");
		
		
		AccountInvoice accountInvoice = null;
		List<AccountInvoiceDetail> accountInvoiceDetails = null;
		//打包主表
		
		accountInvoice = accountInvoiceService.packing(billType, billTypeName, systemCode, flowType, revOpay, direction, autoCode, origin, originName, billNo, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		
		accountInvoice.setRetailFlag(storageRecord.getRetailFlag());
		accountInvoice.setGuestNumber(storageRecord.getGuestNumber());
		
		
		//现结
		accountInvoice.setCashSettle(cashSettle);
		accountInvoice.setSettleCategory(storageRecord.getSettleCategory());
		accountInvoice.setSettleCategoryLabel(storageRecord.getSettleCategoryLabel());
		
		accountInvoice.setComments("系统生成");
		
		accountInvoice.setOrigin(storageRecord.getBillType());
		accountInvoice.setOriginName(storageRecord.getBillTypeName());
		accountInvoice.setOriginNo(storageRecord.getRecordNo());
		
		accountInvoice.setEmployeeNo(storageRecord.getEmployeeNo());
		accountInvoice.setEmployeeName(storageRecord.getEmployeeName());

		accountInvoice.setDealObject(storageRecord.getStorageTypeD());
		accountInvoice.setDealObjectLabel(storageRecord.getStorageTypeDLabel());
		accountInvoice.setCustomerID(storageRecord.getProviderID());
		accountInvoice.setCustomerNo(storageRecord.getProviderNo());
		accountInvoice.setShortName(storageRecord.getShortName());
		accountInvoice.setCustomerName(storageRecord.getProviderName());
		
		accountInvoice.setTaxType(storageRecord.getTaxType());
		accountInvoice.setTaxTypeLabel(storageRecord.getTaxTypeLabel());
		accountInvoice.setTaxRate(storageRecord.getTaxRate());
		
		accountInvoice.setInvoiceCategory(storageRecord.getInvoiceCategory());
		accountInvoice.setInvoiceCategoryLabel(storageRecord.getInvoiceCategoryLabel());
		
		accountInvoice.setOrderNo(storageRecord.getOrderNo());
	
		accountInvoice.setDirection(storageRecord.getDirection());
		
		BigDecimal bgDirection = new BigDecimal(direction);
		
		//累计主表合计金额
		accountInvoice.setItemAmount(storageRecord.getItemAmount());
		accountInvoice.setOrderAmount(storageRecord.getOrderAmount());
		accountInvoice.setOrderAmountOld(storageRecord.getOrderAmountOld());
		accountInvoice.setOrderAmountTax(storageRecord.getOrderAmountTax());
		accountInvoice.setOrderAmountTotal(storageRecord.getOrderAmountTotal());
		
		accountInvoice.setDepositRate(storageRecord.getDepositRate());
		
		accountInvoice.setDiscountAmount(storageRecord.getDiscountAmount());
		accountInvoice.setDiscountRate(storageRecord.getDiscountRate());
		
		//账金额，保留两位小数
		BigDecimal accountAmountOld = accountInvoice.getOrderAmountOld().multiply(bgDirection);
		accountAmountOld.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
		BigDecimal accountAmountTax = accountInvoice.getOrderAmountTax().multiply(bgDirection);
		accountAmountTax.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
		BigDecimal accountAmountTotal = accountInvoice.getOrderAmountTotal().multiply(bgDirection);
		accountAmountTotal.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
		accountInvoice.setAccountAmountOld(accountAmountOld);
		accountInvoice.setAccountAmountTax(accountAmountTax);
		accountInvoice.setAccountAmountTotal(accountAmountTotal);
		
		accountInvoice.setPendingAmount(accountInvoice.getOrderAmountTotal());
//		accountInvoice.setAccountPending(accountAmountTotal);
		
		
		//子表
		List<StorageRecordDetail> storageRecordDetails = storageRecordDetailService.getByMasterID(storageRecord.getfID());
		if(storageRecordDetails.size()>0){
			accountInvoiceDetails = new ArrayList<AccountInvoiceDetail>();
		}
		for(StorageRecordDetail storageRecordDetail : storageRecordDetails){
			AccountInvoiceDetail accountInvoiceDetail = accountInvoiceDetailService.packing(accountInvoice);
			accountInvoice.setMaxDetailNo(accountInvoice.getMaxDetailNo()+1);
			accountInvoice.setDetailsCount(accountInvoice.getDetailsCount()+1);
			
			accountInvoiceDetail.setOrigin(storageRecordDetail.getBillType());
			accountInvoiceDetail.setOriginName(storageRecordDetail.getBillTypeName());
			accountInvoiceDetail.setOriginNo(storageRecordDetail.getRecordNo());
			accountInvoiceDetail.setOriginSerialNo(storageRecordDetail.getSerialNo());
			
			accountInvoiceDetail.setSbomID(storageRecordDetail.getSbomID());
			accountInvoiceDetail.setLv(storageRecordDetail.getLv());
			accountInvoiceDetail.setSttts(storageRecordDetail.getSttts());
			
			//物料
			accountInvoiceDetail.setItemID(storageRecordDetail.getItemID());
			accountInvoiceDetail.setItemNo(storageRecordDetail.getItemNo());
			accountInvoiceDetail.setItemName(storageRecordDetail.getItemName());
			accountInvoiceDetail.setItemDescribe(storageRecordDetail.getItemDescribe());
			accountInvoiceDetail.setItemProperty(storageRecordDetail.getItemProperty());
			accountInvoiceDetail.setUnitCode(storageRecordDetail.getUnitCode());
			accountInvoiceDetail.setUnitName(storageRecordDetail.getUnitName());
			
//			accountInvoiceDetail.setFactoryID(storageRecordDetail.getFactoryID());
//			accountInvoiceDetail.setFactoryNo(storageRecordDetail.getFactoryNo());
//			accountInvoiceDetail.setFactoryName(storageRecordDetail.getFactoryName());
			
//			accountInvoiceDetail.setStorageType(storageRecordDetail.getStorageType());
//			accountInvoiceDetail.setStorageTypeLabel(storageRecordDetail.getStorageTypeLabel());
//			accountInvoiceDetail.setStorageID(storageRecordDetail.getStorageID());
//			accountInvoiceDetail.setStorageNo(storageRecordDetail.getStorageNo());
//			accountInvoiceDetail.setStorageName(storageRecordDetail.getStorageName());
//			accountInvoiceDetail.setFloorNo(storageRecordDetail.getFloorNo());
			
			accountInvoiceDetail.setEmployeeNo(storageRecordDetail.getEmployeeNo());
			accountInvoiceDetail.setEmployeeName(storageRecordDetail.getEmployeeName());

			accountInvoiceDetail.setDealObject(storageRecordDetail.getStorageTypeD());
			accountInvoiceDetail.setDealObjectLabel(storageRecordDetail.getStorageTypeDLabel());
			accountInvoiceDetail.setCustomerID(storageRecordDetail.getProviderID());
			accountInvoiceDetail.setCustomerNo(storageRecordDetail.getProviderNo());
			accountInvoiceDetail.setShortName(storageRecordDetail.getShortName());
			accountInvoiceDetail.setCustomerName(storageRecordDetail.getProviderName());
			
			accountInvoiceDetail.setTaxType(storageRecordDetail.getTaxType());
			accountInvoiceDetail.setTaxTypeLabel(storageRecordDetail.getTaxTypeLabel());
			accountInvoiceDetail.setTaxRate(storageRecordDetail.getTaxRate());
			
			//单价
			accountInvoiceDetail.setItemPrice(storageRecordDetail.getItemPrice());
			accountInvoiceDetail.setDiscountRate(storageRecordDetail.getDiscountRate());
			accountInvoiceDetail.setDiscountAmount(storageRecordDetail.getDiscountAmount());
			accountInvoiceDetail.setDealPrice(accountInvoiceDetail.getItemPrice());
			//数量
			accountInvoiceDetail.setItemAmount(storageRecordDetail.getPriceAmount());
			
			accountInvoiceDetail.setOrderAmount(storageRecordDetail.getOrderAmount());
			accountInvoiceDetail.setOrderAmountOld(storageRecordDetail.getOrderAmountOld());
			accountInvoiceDetail.setOrderAmountTax(storageRecordDetail.getOrderAmountTax());
			accountInvoiceDetail.setOrderAmountTotal(storageRecordDetail.getOrderAmountTotal());

			accountInvoiceDetail.setBillDate(storageRecordDetail.getOrderDate());
			accountInvoiceDetail.setOrderNo(storageRecordDetail.getOrderNo());
			accountInvoiceDetail.setProjectNo(storageRecordDetail.getProjectNo());
			
			accountInvoiceDetails.add(accountInvoiceDetail);
		}
		
		//写入数据库主表
		accountInvoiceService.insert(accountInvoice);
		
		//插入子表
		if(accountInvoiceDetails!=null){
			for(AccountInvoiceDetail accountInvoiceDetail :accountInvoiceDetails){
				accountInvoiceDetailService.insert(accountInvoiceDetail);
			}
		}

		return accountInvoice;
	}
	
	//删除销售发票
	@Transactional
	@Override
	public int accountInvoiceDelete(AccountInvoice accountInvoice){
		if(accountInvoice==null){return -1;}
		//判断是否可以删除
		if(!accountInvoice.getState().equals("active")){return -2;}
		
		String fID = accountInvoice.getfID();
		System.out.println("fID-->"+fID);
		//首先删除从表
		List<AccountInvoiceDetail> accountInvoiceDetails = accountInvoiceDetailService.getByMasterID(fID);
		for(AccountInvoiceDetail accountInvoiceDetail:accountInvoiceDetails){
			accountInvoiceDetailService.delete(accountInvoiceDetail.getfID());
		}
		//删除主表
		accountInvoiceService.delete(fID);

		return 0;
	}
	

    
}
